Vue 父子组件及同级组件之间的传值
1.父组件 father.vue
<template>
<div id="father">
<h2>父组件</h2>
<p>数值:{{m}}</p>
<son1 v-on:giveFather='giveFather'></son1>
<son2></son2>
</div>
</template>
<script>
import son1 from './son1'
import son2 from './son2'
export default {
data(){
return {
m:''
}
},
name:'father',
components:{
son1,
son2
},
methods:{
giveFather: function(childValue) {
// childValue就是子组件传过来的值
this.m = childValue
}
}
}
</script>
2.子组件1 son1.vue
<template>
<div id="son1">
<h2>子组件1</h2>
<button @click='push'>向兄弟组件传值</button>
<button @click='give'>向father组件传值</button>
</div>
</template>
<script>
import bus from '../../assets/eventBus'
export default {
methods:{
push(){
bus.$emit("userDefinedEvent","this message is from son1 to son2");
},
give(){
this.$emit('giveFather',"this message is from son1 to father")
}
}
}
</script>
3.子组件2 son2.vue
<template>
<div id="son2">
<h2>子组件2</h2>
<p>数值:{{msg}}</p>
</div>
</template>
<script>
import bus from '../../assets/eventBus'
export default {
data(){
return {
msg:''
}
},
mounted(){
var self = this;
bus.$on("userDefinedEvent",function(msg){
self.msg=msg;
});
}
}
</script>
4.中央事件总线
同级组件传值时,需要添加中央数据总线 在src/assets/下创建一个eventBus.js,内容如下
(eventBus中我们只创建了一个新的Vue实例,以后它就承担起了组件之间通信的桥梁了,也就是中央事件总线。)
import Vue from 'Vue' export default new Vue
5.效果


5.总结
子组件向父组件传值时,在响应该点击事件的函数中使用$emit来触发一个自定义事件,并传递一个参数。在父组件中的子标签中监听该自定义事件并添加一个响应该事件的处理方法 ;
同级组件传值时,用到bus.$emit和bus.$on两个自定义事件,并需要创建并添加中央数据总线

浙公网安备 33010602011771号