
No more than code.
父值子:
:info="info"
;子组件用props接收:props:["info"]
this.$broadcast('属性', '值')
;子组件events中接收。子值父:
this.$dispatch('属性', '值')
;父组件events中接收。this.$emit('属性', '值')
;父组件@属性="父组件方法名"
,方法接收参数val,也就是子组件传递的值。provide/inject 是 vue2.2.0 新增的 api
provide: { testaaa: "hahaha" }
inject: ["testaaa"]
无论子组件嵌套有多深, 只要调用了inject 就可以注入 provide 中的数据;
通过sync修饰符,来实现子组件更新父组件状态,是目前写法上最方便的语法糖了。
1、父组件声明状态active
<compo :foo.sync="active"></compo>
这种语法糖其实会被解析成
<compo :foo="active" @update:foo="val => active = val"></compo>
2、子组件修改父组件active的值:
this.$emit('update:foo', newValue)
// bus
const bus = new Vue();
// 数据接收组件
bus.$on('event1', (val)=>{});
// 数据发出组件
bus.$emit('event1', val);
升级版
// bus
const bus = new Vue({
data () {
return {
val1: ''
}
},
created () {
this.$on('updateData1', (val)=>{
this.val1 = val
})
}
})
// 数据发出组件
bus.$emit('updateData1', val)
// 数据接收组件 == 使用computed接收数据
computed () {
val1 () {
// 依赖并返回bus中的val1
return bus.val1
}
}
通常我们监听组件生命周期会使用 $emit ,父组件接收事件来进行通知
// 子组件
export default {
mounted() {
this.$emit('listenMounted')
}
}
// 父组件
<template>
<div>
<List @listenMounted="listenMounted" />
</div>
</template>
其实还有一种简洁的方法,使用 @hook 即可监听组件生命周期,组件内无需做任何改变。同样的, created 、 updated 等也可以使用此方法。
<template>
<List @hook:mounted="listenMounted" />
</template>