第一种:props
适用场景:父子组件通信
注意事项:
如果父组件给子组件传递数据(函数):本质上上是子组件给父组件传递数据
如果父组件给子组件传递的数据(非函数),本质上是父组件给子组件传递数据
书写方式: 3种
['todos]、{type:Array}、{type:Array, default:[]}
第二种:自定义事件
适用场景:子组件给父组件传递数据
$on、$emit $off
子组件传递值:
this.$emit('personalEvent', this.name);
父组件接受值:
mounted() {
this.$refs.student.$on('personalEvent', (name) => {
console.log(this);
console.log(name);
this.studentName = name;
});
}
第三种:全局事件总线$bus
适用场景:万能
Vue.prototype.$bus = this;
new Vue({
el:'#app',
render: h => h(App),
beforeCreate() {
Vue.prototype.$bus = this; //安装全局事件总线
}
});
子组件:
this.$bus.$emit('hello', this.name);
父组件:
mounted() {
console.log('School', this);
this.$bus.$on('hello', (data) => {
console.log(`我是School组件,我收到了数据,${data}`);
})
},
beforeDestroy() {
this.$bus.$off('hello'); //销毁解绑
}
第四种:消息订阅和发布 pubsub-js,在React框架中使用的比较多(发布、订阅)
适用场景:万能
发布消息:
pubsub.publish('hello', this.name);
订阅消息:
mounted() {
// console.log('School', this);
// this.$bus.$on('hello', (data) => {
// console.log(`我是School组件,我收到了数据,${data}`);
// })
//订阅消息 隔空对讲机喊话
this.pubId = pubsub.subscribe('hello', (name, msg) => {
//注意这里写剪头函数this才不会丢
console.log(`有人发布了hello消息,回调被执行,data: ${msg}`);
});
},
beforeDestroy() {
// this.$bus.$off('hello'); //销毁解绑
//取消订阅
pubsub.unsubscribe(this.pubId); //取消订阅
}
第五种:VueX多组件数据共享
适用场景:万能
5.1main.js文件配置:
new Vue({
el: '#app',
store,
render: h => h(App),
});
5.2创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state,
getters
});
5.3 引入与使用
import { mapState, mapGetters, mapMutations, mapActions} from 'vuex';
computed:{
... mapState(['sum', 'school', 'subject', 'personList']),
...mapGetters(['bigSum']),
}
methods:{
...mapActions(['incrementWait', 'incrementIfOdd']), //数组写法,同上
...mapMutations({
increment: 'INCREMENT',
decrement: 'DECREMENT',
}), //对象写法
...mapMutations(['increment', 'decrement']),//数组写法
incrementOdd(){
this.$store.dispatch('incrementIfOdd', this.n);
},
}
第六种:插槽
适用场景:父子组件通信--(一般传递的是结构)
默认插槽
具名插槽:
<slot name="center">我是默认值</slot>
<slot name="footer">我是默认值</slot>
<Category title="美食">
<img slot="center" src="" alt="delicious food"/>
<a href="https://www.baidu.com" slot="footer">百度</a>
</Category>
作用域插槽:
<slot :games="games">
我是默认值
</slot>
<Category title="游戏">
<template slot-scope="{games}">
<h4 v-for="(g , index) in games" :key="index">{{ g }}</h4>
</template>
</Category>