vue组件间的通信
Vue中 a t t r s 、 attrs、 attrs、listeners 详解及使用_明天也要努力的博客-CSDN博客_$attrs
父组件向子组件传值
- 父向子传递数据是通过props,子向父传递数据是通过events($emit)
- 通过 父链/子链 也可以通信($parent / $children)
- ref 也可以访问组件实例
- provide / inject
- $attr / $listeners
// msg为父组件要传递给子组件的值
<Father :msg='msg'></Father>
// 子组件接收:
props:{
msg:数据类型
}
或
props:['msg']
// 实例
Vue.component('Child',{
template:`
<div>
<h3>我是一个子组件</h3>
<h4>{
{childData}}</h4>
</div>
`,
props:['childData']
})
const App = {
data() {
return {
msg: '我是父组件传进来的值'
}
},
template: `
<div>
<Child :childData = 'msg'></Child>
</div>
`
}
子组件向父组件传值
// changVal为vue要观察改变的值,'child'为自定义事件名称
watch:{
changeVal(){
this.$emit("child",this.changeVal)
}
}
// 父组件接收:
<Father @child=""></Father>
兄弟组件的之间的传参
- Bus
- Vuex
// 组件一:传递
data(){
return{
todoList:''
}
},
methods:{
addList:function(){
// 使用$emit自定义事件
eventBus.$emit('add',this.todoList)
}
}
// 组件二:接收
created:function(){
this.acceptList()
},
methods:{
acceptList:function(){
// 重点:$on接收事件
eventBus.$on('add',(message)=>{
this.lists.push({
name:message,isFinish:false})
})
}
}
- 跨级通信
- Bus
- Vuex
- provide / inject
- $attrs / $listeners
- 实例
- father.vue
<template>
<div id='app'>
<Child1 :pChild1='child1' :pChild2="child2" :pChild3="child3" @method1="onMethod1" @method2="onMethod2"></Child1>
</div>
</template>
<script>
import Child1 from "./child1-app.vue";
export default {
name: "father-app",
data() {
return {
child1: "father-app向child1传递的数据",
child2: "father-app向child2传递的数据",
child3: {
name: 'father-app向child3传递的数据'
}
}
},
components: {
Child1
},
methods: {
onMethod1(msg1) {
console.log(`${msg1} running in father-app`)
},
onMethod2(msg2) {
console.log(`${msg2} running in father-app`)
}
}
}
</script>
- son.vue
<template>
<div class='child1'>
<h2> In Child1</h2>
<h2>props:{
{ pChild1 }}</h2>
<p>$attr:{
{ $attrs }}</p>
<!-- 通过v-bind绑定$attrs属性,C组件可以直接获取到A组件中传递下来的props(除了B组件中props声明的) -->
<!-- C组件中能直接触发test的原因在于 B组件调用C组件时 使用 v-on 绑定了$listeners 属性 -->
<Child2 v-bind="$attrs"></Child2>
<hr/>
</div>
</template>
<script>
import Child2 from "./child2-app.vue";
export default {
name: "child1-app",
data() {
return {
child1: "child1"
}
},
props: {
pChild1: {
type: String
}
},
components: {Child2},
// 当inheritAttrs为 true时,浏览器控制台会显示出传递的数据
inheritAttrs: true,
mounted() {
this.$emit('method1', this.child1)
}
}
</script>
- grandson.vue
<template>
<div class="child2">
<h2> In Child2</h2>
<h2>{
{ pChild2 }}</h2>
<p>$attrs: {
{ $attrs }}</p>
<p>pChild3: {
{ $attrs.pChild3.name }}</p>
</div>
</template>
<script>
export default {
name: "child2-app",
data() {
return {
child2: "child2"
}
},
props: {
pChild2: {
type: String
}
},
inheritAttrs: true,
mounted() {
this.$emit('method2', this.child2)
}
}
</script>
- 效果