Vue.js组件通信方式总结
Vue组件之间的通信主要有三种:父-子通信,子-父通信,跨级通信。
- 父子通信
<body>
<div id='app1'>
这里是实例
{{sum}}
<hr>
<!-- 在son组件标签上使用 xixi自定义属性 -->
<son :xixi='sum'></son>
</div>
<!-- 组件模板 -->
<template id='son'>
<div class='son'>
这里是组件
{{xixi}}
</div>
</template>
<script>
Vue.component('son',{
template:'#son',
data(){
return{
hehe:123
}
},
props:{
xixi:{type:Number} //传值的同时检查数据的类型
}
})
let vm1 = new Vue({
el:'#app1',
data:{
sum:5
}
})
</script>
</body>
不管是组件还是实例,自己的数据只能自己使用,如果子组件想用父组件的数据,就要在子组件上添加一个自定义属性,然后在子组件下用props接收,就能实现将父组件的数据传给子组件,接受完了就可以在组件里直接使用,但是只能用不能改。
- 子父通信
<body>
<div id='app1'>
这里是实例{{sum}}
<hr>
<!-- 绑定在son身上的自定义事件 事件名叫 custom 处理函数叫add -->
<son @hehe='change'></son>
</div>
<!-- 组件模板 -->
<template id='son'>
<div>
这里是子组件
<button @click='sonClick'> 这里是子组件的按钮</button>
</div>
</template>
<script>
Vue.component('son',{
template:'#son',
methods: {
sonClick(){
console.log('子组件的处理方法')
// 通过emit方法触发自定义事件 参数1 自定义事件名
this.$emit('hehe')
}
},
})
let vm1 = new Vue({
el:'#app1',
data:{
sum:5
},
methods: {
change(num){
this.sum++
}
},
})
</script>
</body>
子父通信,就是用子组件来修改父组件的属性的,但是不能直接修改,需要在子组件上添加一个自定义事件,值为父组件的方法,然后在子组件里的方法里通过this.$emit()来触发,这样就能在子组件内通过触发父组件的方法来实现子父通信。