一. 传值方法
Bus:也可说是 总线机制、发布订阅模式、观察者模式
-
main.js
中 new 一个 Vue 的实例,挂载在bus
属性上Vue.prototype.bus=new Vue()
-
传值组件
通过
$emit
方法触发事件,同时携带内容methods: { handleClick(){ this.bus.$emit('changeMsg','收到请回答') } },
-
接收值组件
在
mounted
生命钩子中监听 bus 的改变,
通过$on
方法监听 bus 上的事件,接收传递回来的值。mounted() { var this_=this this.bus.$on('change',function(msg){ console.log(msg) }) },
二. 传值实例
传值组件
<template>
<div>
<button @click="sendMsg">传值</button>
</div>
</template>
<script>
export default {
data() {
return {};
},
methods: {
sendMsg() {
this.bus.$emit("changeMsg", "收到请回答");
}
}
};
</script>
<style scoped>
</style>
接收值组件
<template>
<div>
<p>接收消息:{{ msg }}</p>
</div>
</template>
<script>
export default {
data() {
return {
msg: ""
};
},
mounted() {
var this_ = this;
this.bus.$on("changeMsg", function(msg) {
console.log(msg);
this_.msg = msg;
});
}
};
</script>
<style scoped>
</style>