1.props(数据双向绑定,props,可祖传父,父传子能隔代)
将组件中需要传递的东西交给共同的父亲,父亲再将数据交给其中一个儿子,这个过程通过props的方法传递,让son2接收 props['xxx'],此时接收的数据出现在son2的实例对象vc身上,所以模板可以使用。
此时son1要获得数据1,father就要提前创造一个函数传递给son1,然后son1调用函数。此时就可以定义在father中的函数,进行操作,这就意味着只要son1调用函数,vue就会重新解析模板,然后更新数值。
总结:借用父亲创造函数,子组件调用函数并且传参传到父亲创造的函数中
结合todolist案例
<MyFooter :todos="todos" :checkAllTodo=" checkAllTodo" :clearAllTodo="clearAllTodo"/>
props:['todos','checkAllTodo','clearAllTodo'],
methods: {
checkAll(e){
this.checkAllTodo(e.target.checked)
},
deleteAll(value){
this.deleteAllTodo(value)
}
},
2.自定义事件法(v-on/ref,父传子,不能隔代,不用props接收)
1.自定义事件法是组件之间的一种通信方式,适用于子组件传递给父组件。
2. 使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。
3. 绑定自定义事件:
方式一,在父组件中:
<Demo @hello="test"/>或 <Demo v-on:hello="test"/>
方式二,在父组件中:
...... js
<Demo ref="demo"/>
......
mounted(){
this.$refs.xxx.$on('hello',this.test)
}
若想让自定义事件只能触发一次,可以使用once修饰符,或$once方法
4. 触发自定义事件:this.$emit('hello',数据)
5. 解绑自定义事件:this.$off('hello')
6. 组件上也可以绑定原生DOM事件,需要使用```native```修饰符。
7. 注意:通过 this.$refs.xxx.$on('hello',回调)绑定自定义事件时,回调要么配置在methods中要么用箭头函数,否则this指向会出问题!
结合todolist案例
原来App中传递给MyHeader以及MyFooter使用函数传递的地方就可以更改为利用自定义事件去修改.原来使用props接收函数的地方就可以去掉,但是传递数据的地方不能去掉。
将数据双向绑定改为@,调用函数的地方使用$emit
<MyFooter :todos="todos" @checkAllTodo="checkAllTodo" @deleteAllTodo="deleteAllTodo"/>
methods: {
checkAll(e){
this.$emit("checkAllTodo",e.target.checked)
},
deleteAll(value){
this.$emit("deleteAllTodo",value)
}
},
3.全局事件总线(GlobalEventBus)
找出一个公用的都能获取数据的地方,也就是vue。
1. 一种组件间通信的方式,适用于任意组件间通信。
2. 安装全局事件总线:
在main.js中安装
```js
new Vue({
......
beforeCreate() {
Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
},
......
})
```
3. 使用事件总线:
(1). 接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的 回调留在A组件自身。
```js
methods(){
demo(data){......}
}
......
mounted() {
this.$bus.$on('xxxx',this.demo)
}
```
(2). 提供数据 :this.$bus.$emit('xxxx',数据)
4. 最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。
-----提供数据的组件
export default {
name:'Student',
data(){
return{
name:'张三',
sex:'男',
}
},
methods:{
sendStudentName(){
this.$bus.$emit('hello',this.name)
}
}
}
-----接收数据的组件
mounted(){
// console.log("School",this.x);
this.$bus.$on('hello',(data)=>{
console.log('我是school组件,收到了数据',data);
})
},
beforeDestroy(){
this.$bus.$off('hello')
}
4.消息订阅与发布(任意组件之间)
1. 一种组件间通信的方式,适用于任意组件间通信
2. 使用步骤:
(1)安装pubsub:npm i pubsub-js
(2) 引入: import pubsub from 'pubsub-js
(3)接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。
```js
methods(){
demo(data){......}
}
......
mounted() {
this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息
}
```
4. 提供数据:pubsub.publish('xxx',数据)
5. 最好在beforeDestroy钩子中,用 PubSub.unsubscribe(pid)去取消订阅。