vue组件通信分为父组件=>子组件,子组件=>父组件,兄弟组件之间、祖先和后代之间以及任意两个组件之间的通信;
这里props有两种写法:
方法一:(直接引入不做任何初始处理, props以数组的形式引入)
props: ["msg"]
方法二:(对prop属性做验证,可以规定props属性的类型、初始值等,当父组件传递的参数不对时,vue会给出错误提示。这里type类型包括 :Object,String,Number,Boolean,Function, Array,Symbol)
props: { msg: {
//类型是字符串且设置默认值(当父组件没有传递参数是,默认值会生效) type: String,default: "初始值" }
//可以规定多种类型
msg1: [String, Number],
//规定必传
msg2:{
type: String,
required: true
}
//数组和对象的方法返回默认值应当以函数形式返回
msg3: {
type: Object,
default: () => {
return { msg: "sss" }
}
} }
2.$attrs
子组件也可以直接通过使用$attrs属性获取父组件的参数
父组件
<helloWorld attr="属性值"></helloWorld>
子组件
<p>{{ $attrs.attr }}</p>
3.通过引用refs
//父组件
<helloWorld refs="hello"></helloWorld>
mounted () {
this.$refs.hello.msg = "sdf";
}
//子组件 (首先msg必须在data里面有声明,父组件才能传递值给子组件里的msg)
data () {
return {
msg: ""
}
}
4.通过$children
//父组件
mounted () {
var arr = this.$children; //arr 得到的是子组件的集合(但这个集合不保证顺序)
this.$children[0].msg = "修改"; //给相应的子组件传值
}
子组件通过自定义事件方法向父组件传递参数:(使用this.$emit方法)
兄弟之间组件的通信通过共同的祖先组件或根组件搭建桥梁,即$parent 或 $root
//兄弟组件1 helloWorld1.vue,通过this.$parent.$emit(event, params)自定义事件触发向他的兄弟组件传递参数
methods: {
emitClick () {
this.$parent.$emit("emitClick", params)
或
this.$root.$emit("emitClick", params)
}
}
//兄弟组件2 helloWorld2.vue,通过this.$parent.$on(event, parmas)监听兄弟组件传递的参数
mounted: {
this.$parent.$on("emitClick", params => {
console.log(params)
})
或
this.$root.$on("emitClick", params => {
console.log(params)
})
}
祖先和后代的通信由于嵌套层级较多,这个时候使用props通信就有点繁琐,可以通过vue提供的provide/inject API来完成
//祖先组件通过provide提供变量,provide的方法的使用和data相同
provide () {
return {
foo: params
}
}
//后代组件通过inject方法注入祖先组件定义的变量,inject注入变量的方式和porps相同
//简单的可以写成,写法和props: ["foo"]相同,这两就直接获取到祖先组件传递的参数
inject: ["foo"]
事件总线的实现:通过创建一个bus类实现事件派发、监听和回调管理
//创建一个bus.js文件
class Bus () {
constructor () {
this.callbacks = {}
}
$on (name, fn) {
this.callbacks[name] = this.callbacks[name] || []
this.ca..backs[name].push(fn)
}
$emit (name, args) {
if (this.callbacks[name]) {
this.callbacks[name].forEach(cb => cb(args))
}
}
}
//在main.js中引用bus.js
import Bus from ‘bus.js‘
Vue.prototype.$bus = new Bus()
//使用
//组件1 通过this.$bus.$emit触发事件
this.$bus.$emit(‘emitClick‘, params)
组件2 通过this.$bus.$on监听事件的发生
this.$bus.$on("emitClick", params => {
console.log(params) //获取组件1 传递的参数
})
原文:https://www.cnblogs.com/michen/p/11610670.html