<body>
<script src="../libs/vue.js"></script>
<div id="app">
<com1></com1>
<!--com2给com1发消息-->
<com2></com2>
</div>
<template id="temp1">
<div>
<h2>com1子组件的数据</h2>
</div>
</template>
<template id="temp2">
<div>
<h2>com2子组件的数据</h2>
<button @click="sendMessage">发送消息</button>
</div>
</template>
<script>
/*创建一个全局的bus属性*/
/*bus是自定义的全局属性,可更改*/
Vue.prototype.bus = new Vue();
Vue.component('com1', {
template: '#temp1',
mounted(){
//接收消息
this.bus.$on('click',(msg)=>{
console.log(msg)
})
}
})
Vue.component('com2', {
template: '#temp2',
data(){
return{
message:'com2的私有数据'
}
},
methods: {
/*发送消息*/
sendMessage() {
this.bus.$emit("click", this.message)
}
}
})
var app = new Vue({
el: '#app',
data: {
message: '',
},
})
</script>
</body>