<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>4-5非父子组件的传值</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<body>
<div id="root">
<child content="郑"></child>
<child content="丰"></child>
</div>
</body>
<script type="text/javascript">
Vue.prototype.bus = new Vue();
Vue.component('child',{
data: function(){
return {
selfContent: this.content
}
},
// props:['content'],
props:{
content:String
},
template: '<div @click="handleClick">{{selfContent}}</div>',
methods: {
handleClick: function(){
alert(this.selfContent);
//console.log(this.selfContent);
//这个bus是一个vue实例,所以就会有emit属性
this.bus.$emit('ca',this.selfContent);
}
},
// 生命周期钩子
mounted: function(){
//这样子组件都是监听到
var this_ = this;
this.bus.$on('ca',function(msg){
// console.log(count++);
// console.log("dd"+msg);
this_.selfContent = msg
})
}
});
var vm = new Vue({
el: "#root"
})
</script>
</html>
课程紧跟Vue3版本迭代,企业主流版本Vue2+Vue3全掌握
了解课程