<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="root">
<child content="Nay"></child>
<child content="Ek"></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() {
return {
selfContent : this.content
}
},
props: {
content: String
},
template: '<div @click="handleClick">{{selfContent}}</div>',
methods: {
handleClick() {
this.bus.$emit('change', this.selfContent)
}
},
mounted() {
// var that = this
// this.bus.$on('change', function(msg) {
// 这里this的指向发生了变更所以需要提前保存this,或者用箭头函数解决
// that.content = msg
// })
this.bus.$on('change', (msg) => {
this.selfContent = msg
})
}
})
var vm = new Vue({
el: '#root'
})
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/nayek/p/11865156.html
时间: 2024-10-08 23:20:08