这里记录父组件和子组件数据传输,和兄弟组件之间的数据传输
首先·先建立父组件,兄弟组件
<div id="event1">
<text-input v-bind:message="message" v-on:onfocus = "onfocus"></text-input>
<p>父组件:{{message}}</p>
<div :style="{ fontSize: size + 'em' }">
<text-cp v-bind:size="size" v-on:changebig="changebig"></text-cp>
</div>
</div>
text-input 和 text-cp 是一对兄弟组件
文本框在text-input中,我们要达到的目的是,改文本框内容,父组件实时响应,点击"点我按钮" 兄弟组件更新值
点击click 按钮,兄弟组件字体变大
父组件
new Vue({
el: "#event1",
data: () => {
return {
size: 1,
message: "aaa"
}
},
methods: {//不能使用箭头函数,否则this会出错
changebig: function (a) {
this.size += a //字体变大函数
},
onfocus: function (a) {
this.message = a //父组件文本值变化函数
}
},
})
text-input组件
Vue.component("text-input", {
props: ["message"],
data: function () {//这里不能写箭头函数,要使用this
return { messages: this.$props.message }
},
methods: { //不能使用箭头函数
textclick:function(a){
hub.$emit("message-to",a)
}
},
template: `<div>
<input type="text" v-model="messages" v-on:keyup = "$emit('onfocus',messages)">
<button v-on:click = "textclick(messages)">点我</button>
</div>
`
})
我们先考虑和父组件的事件 ,暂时忽略 methods 属性。
因为有 v-model 文本框内容会实时更新进 messages
为input绑定原生事件 keyup ,去触发父组件的 onfocus 事件,并带有参数
在html上,为此组件传参 然后绑定事件监听器,监听会触发的父组件事件 onfocus
<text-input v-bind:message="message" v-on:onfocus = "onfocus"></text-input>
text-cp组件
Vue.component("text-cp", {
props: ["size"],
mounted: function () { //被挂载后调用
hub.$on('message-to', (text) => {
this.message = text
})
},
data: () => {
return { message: "你好" }
},
template: `<div class="text-cp">
<p>兄弟组件:{{message}}</p>
<button v-on:click="$emit('changebig',0.2)">chick me change big</button>
</div>`
})
同样,我们先考虑和父组件事件
为button绑定原生事件 click,去触发父组件的 changbig 事件
在html上,为此组件传参 然后绑定事件监听器,监听会触发的父组件事件 changbig
<div :style="{ fontSize: size + 'em' }">
<text-cp v-bind:size="size" v-on:changebig="changebig"></text-cp>
</div>
兄弟组件事件
为了兄弟组件之间通信,我们创建一个中转组件
let hub = new Vue()
然后我们在text-cp里监听hub的自定义事件 message-to , 把参数data 赋给自己的 message
在text-input 里 通过 button绑定原生事件来触发 hub的自定义事件 message-to ,并传值
(灵感来源,黑马程序员教程)