1 概述:
vue组件间的传值,父子之间props 和emit; 跨组件间可以使用vuex或者eventBus;
eventBus 即const bus = new Vue(); 通过 vue的on 触发和监听,进行值的传递;
2 Demo
项目结构
- test1. vue
- test2.vue
- parent.vue
- eventBus.js
代码示例
*eventBus.js
import Vue from 'vue'
let Bus = new Vue({
data: function () {
return {
a: 1,
}
}
});
export { Bus }
*test1.vue
<template>
<div>
<p>test1</p>
<div>{{testA}}</div>
<button @click="handleClick">clickA</button>
</div>
</template>
<script>
import { Bus } from "./../eventBus";
export default {
name: "testA",
data: function() {
return {
testA: 1
};
},
methods: {
handleClick() {
this.testA++;
Bus.$emit("handleTestA", this.testA);
}
}
};
</script>
- test2.vue
<template>
<div>
<p>test2</p>
<div>{{testB}}</div>
<button @click="handleClick">clickB</button>
</div>
</template>
<script>
import { Bus } from "./../eventBus";
export default {
name: "testB",
data: function() {
return {
testB: 1
};
},
methods: {
handleClick() {
this.testB++;
Bus.$emit("handleTestB", this.testB);
}
}
};
</script>
*parent.vue
<template>
<div>
<p>parent</p>
<testA></testA>
<testB></testB>
<div>
<h3>testA{{receivedTestA}}</h3>
<h3>testB{{receivedTestB}}</h3>
</div>
</div>
</template>
<script>
import { Bus } from "./../eventBus";
import testA from "./test1";
import testB from "./test2";
export default {
name: "aaa",
data: function() {
return {
receivedTestA: "",
receivedTestB: ""
};
},
components: {
testA,
testB
},
mounted: function() {
Bus.$on("handleTestB", val => {
this.receivedTestA = val;
});
Bus.$on("handleTestA", val => {
this.receivedTestB = val;
});
},
methods: {}
};
</script>
3 结果示例

网友评论