父组件 -->子组件
- 属性props
//child
props:{msg:String}
//parent
<HelloWorld msg="***********"/>
- refs
//parent
<HelloWorld ref="hw"/>
//赋值
this.$refs.hw.msg = "******";
- children
//parent
this.$children[0].msg = "****";
子组件-->父组件
- 自定义事件
//chidren
this.$emit("add",data);
//parent
<HelloWorld @add="funcName"/>
-
.sync修饰符
*实现父子组件数据的双向绑定
官网:https://cn.vuejs.org/v2/guide/components-custom-events.html#sync-%E4%BF%AE%E9%A5%B0%E7%AC%A6
//父组件语法 v-bind:propName.sync = "data";
// v-bind.sync="obj";[这种语法只适用于对象]
//子组件语法 com.$emit("update:propName",newData)
//parent
<Hello1 v-bind:msg.sync="msg"></Hello1>
<Hello2 v-bind.sync = "myData"></Hello2>
data() {
return {
msg: "msgmsgmgsg",
myData:{
a:1,b:2,c:3
}
}
}
//Hello1
fun1() {
this.$emit("update:msg","hello1的新数据")
}
//Hello2
/* myData对象中的每一个属性 (如a) 都作为一个独立的 prop 传入,
各自添加用于更新的 v-on 监听器*/
fun1() {
this.$emit("update:a","ahello2的新数据")
this.$emit("update:b","bhello2的新数据")
this.$emit("update:c","chello2的新数据")
}
兄弟组件
- 通过共同的祖辈组件$parent/$root
// brother1 监听事件
created () {
this.$parent.$on("fun1",()=>{
console.log("there is hello2")
});
}
// brother2 触发事件
<div @click="$parent.$emit('fun1')">
<h1>HelloWorld1</h1>
</div>
事件由谁派发就由谁监听;
$on和v-on的区别
https://www.cnblogs.com/surfer/p/9815692.html
$on 监听实例的事件
v-on监听dom的事件
祖先和后代之间
- provide/inject:能够实现祖先给后代传值
// ancestor
provide() { return {foo: 'foo'} }
// descendant
inject: ['foo']
*适用于多层嵌套,但传值不建议修改,且该方法多见于开源组件,日常开发不建议使用;
*不能适用于后代向祖先传值;
任意两个组件之间
- 事件总线:创建一个Bus类负责事件派发、监听和回调管理
// Bus:事件派发、监听和回调管
class Bus{
constructor(){
this.callbacks = {}
}
$on(name, fn){
this.callbacks[name] = this.callbacks[name] || [] this.callbacks[name].push(fn)
}
$emit(name, args){
if(this.callbacks[name]){
this.callbacks[name].forEach(cb => cb(args))
}
}
}
// main.js
Vue.prototype.$bus = new Bus();
Vue.prototype.$bud = new Vue();
// com1
this.$bus.$on('foo', callback);
// com2
this.$bus.$emit('foo',data);
- vuex:创建唯一的全局数据管理者store,通过它管理数据并通知组件状态变更