说一说vue组件间的通信?
1.props,$emit,sync
props父组件绑定传值,子组件声明props接收
props接收值原则上不允许改变,但对于对象属性改变,可能不会被vue检测到
$emit,绑定事件,子组件触发事件传递参数
父组件绑定@
子组件触发
this.$emit('father',this.ldh)
sync,es6后的语法糖
父组件
2.全局事件总线
beforeCreate(){
Vue.prototype.$bus = this //安装全局事件总线
}
绑定事件:
mounted(){
// 绑定自定义事件
this.$bus.$on('自定义事件名', (接收参数)=>{
console.log('我是TestB组件,收到了数据', 接收参数);
})
}
触发事件
methods:{
// 触发事件,事件名不能重复
触发事件方法名(){
this.$bus.$emit('自定义事件名', 传递参数);
}
},
3.provide与inject
用于后代间传值
provide提供数据,inject接收
父组件:
provide() {
return {
num: this.num
};
}
子组件:
inject: ['num']
4.parent,children
获取子组件,父组件
this.$parent
this.$children
5.ref
ref用于标签上是是获取该dom元素,用于组件上是获取该组件实例
<child ref='one'></child>
this.$refs.one
类似$children
6.$attrs / $listeners
获取props未接收到的值
一般用于后代组件中传值,
传递给孙子组件时,要绑定
<GrandChild v-bind="$attrs"></GrandChild>
7.Vuex
vuex是vue全家桶中一个重要的插件
要安装
store中五个属性
state:用于保存数据
mutations:对数据进行改变,在此不能进行异步操作
actions:处理业务逻辑,一般在此可以进行异步操作,
getters:类似于计算属性
moudle:模块化
使用:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
address:'SCNU',
phone:"15815379394"
},
mutations:{
Change(state,num){
console.log(state,num)
}
},
actions:{
change(context,num){
console.log(context,num)
}
},
getters:{
}
})
原则上只有mutations中的方法才能改变state中的值,但actions也能改变,但不会被开发者工具监测到,
actions中的方法用dispatch触发
mutations中的方法用commit触发
都是两个参数,第一个参数为要触发的函数,第二个参数是要传递的数据
还有4个map辅助函数来减少代码量