<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>非父子组件之间的传值</title>
</head>
<body>
<div id="app">
<child content="Dell"></child>
<child content="Lee"></child>
</div>
<!-- 开发环境版本,包含了用帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript">
Vue.prototype.bus = new Vue();
Vue.component('child', {
data: function() {
return {
selfContent: this.content
}
},
props: {
content: String
},
template: `<div @click="handleClick">{{selfContent}}</div>`,
methods: {
handleClick: function() {
this.bus.$emit('change', this.selfContent);
}
},
mounted: function() {
var _this = this;
this.bus.$on('change', function(msg) {
_this.selfContent = msg;
})
}
})
var app = new Vue({
el: '#app'
})
</script>
</body>
</html>