1.父传子
建立ComponentA.vue文件
<template>
<div>
<h1>A组件</h1>
<span>消息为:{{message}}</span><br>
<button v-on:click="onclickA">A点击事件</button><br>
<button v-on:click="onclickToB">发送消息到B组件</button>
</div>
</template>
<script>
import Bus from './bus.js'
export default {
props:["message"],
data() {
return {
}
},
methods: {
onclickA(){
this.$emit("onClickA","this is MessageA")
},
onclickToB(){
Bus.$emit("on1","this is MessageA to B")
}
},
}
</script>
父传子通过message属性值传递。
创建Parent.vue 如下
<template>
<div>
<h1>Welcome</h1>
<h3>{{this.messageA}}</h3>
<h3>{{this.messageB}}</h3>
<span>-------------------------------------------</span>
<A message="你好!A组件" v-on:onClickA="onClickA"></A>
<span>-------------------------------------------</span>
<B message="你好!B组件" v-on:onClickB="onClickB"></B>
<span>-------------------------------------------</span>
</div>
</template>
<script>
import A from "./compont/ComponentA.vue";
import B from "./compont/ComponentB.vue";
export default {
components: {
A,
B
},
data() {
return {
messageA: "监听A消息!",
messageB: "监听B消息!"
};
},
methods: {
onClickA: function(messageA) {
this.messageA = messageA;
},
onClickB: function(messageB) {
this.messageB = messageB;
}
}
};
</script>
在Parent.vue中A标签中传入message消息给A组件。
子传父:
代码同上在ComponentA.vue 调用 this.$emit("onClickA","this is MessageA") 作为钩子函数"onClickA" 作为方法名,"this is messageA " 作为参数。
代码同上在Parent.vue 中 v-on:onClickA="onClickA" 子类的传递的参数将传递给Parent 中的onClickA方法。
非父子组件之间的传递
创建ComponentB.vue
<template>
<div>
<h1>B组件</h1>
<span>消息为:{{message}}</span><br>
<button v-on:click="onclickB">点击事件B</button><br>
<span>{{messageA}}</span>
</div>
</template>
<script>
import Bus from './bus.js'
export default {
props: ["message"],
data() {
return {
messageA:"监听来自A的消息!"
}
},
mounted() {
Bus.$on("on1",(msg)=>{
this.messageA=msg
})
},
methods: {
onclickB() {
this.$emit("onClickB", "this is MessageB");
}
}
};
</script>
创建Bus.js 如下:
import Vue from 'vue'
export default new Vue()
通过Bus.js作为通道,在A中调用Bus.$emit("on1","this is MessageA to B")定义一个方法on1的钩子函数,在B中的生命周期mounted中 调用
Bus.$on("on1",(msg)=>{
this.messageA=msg
})
接收A传入的消息;