<body>
<div id="app">
<child content="Dean"></child>
<child content="Wade"></child>
</div>
<script>
Vue.component('child', {
props: {
content: String
},
template: '<div>{
{content}}</div>'
})
var vm = new Vue({
el: '#app',
data: {
},
methods: {
handleClick() {
console.log('root component clicked!')
}
}
});
</script>
</body>
Lo que queremos lograr es cambiar el Wade de abajo a Dean haciendo clic en Dean arriba, y luego haciendo clic en Wade abajo y Dean arriba se convertirá en Wade. Dichos requisitos implican pasar valores entre componentes secundarios y no principales
<body>
<div id="app">
<child content="Dean"></child>
<child content="Wade"></child>
</div>
<script>
// 挂载到Vue的原型上
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() {
// 点击把自己的值传递给另一个组件
this.bus.$emit('change', this.content)
}
},
mounted: function() {
var this_ = this
console.log('this_:', this_)
this.bus.$on('change', function(msg){
this_.selfContent = msg
})
}
})
var vm = new Vue({
el: '#app',
data: {
}
});
</script>
</body>
Preste atención al significado de esto aquí: señale cada componente en sí
y por qué guardar this_ = this