-
父传子
- 属性props
// 父 <HelloWorld msg="Welcome to Your Vue.js App"/> // 子 props: {msg: String} - $attrs(未在props中申明的属性)
// 父 <HelloWorld m1="hello world"/> // 子 <h2>{{$attrs.m1}}</h2> - 引用refs
// 父 <HelloWorld ref="helloWorld"/> this.$refs.helloWorld.m2 = 'no' // 子 data(){ return { m2:'yes' } } - $children 访问子元素
this.$children[0].m2 = 'no'
- 属性props
-
子传递父
- 自定义事件
// 父 <HelloWorld @clk="handle($event)"/> // 子 this.$emit('clk','hello world')
- 自定义事件
-
兄弟组件
- 通过共同的祖辈组件桥接
$parent或$rootthis.$root.$emit('XX','yyy') this.$root.$on('XX',(val)=>{ console.log(val) })
- 通过共同的祖辈组件桥接
-
祖先与后代
-
provide和inject//祖先 export default{ provide(){ // 同data申明 return { app:'you are right' } } } // 后代 export default{ inject:['app'] // 同props申明 }
-
-
任意两个组件之间
- Vuex或者事件总线
Vue.prototype.$bus = new Vue() - 创建一个Bus类负责管理事件监听,派发和回调执行
class Bus{ constructor(){ this.cbs = {} } $on(name,cb){ this.cbs[name] = this.cbs[name] || [] this.cbs[name].push(cb) } $emit(name,args){ if(this.cbs[name]){ this.cbs[name].forEach(cb=>cb(args)) } } }
- Vuex或者事件总线