vue組件之間的通訊

使用props傳遞數(shù)據(jù),組件內(nèi)部

<div id="app1">
<child my-message="組件內(nèi)部數(shù)據(jù)傳遞"></child>
</div>
//js
<script>
Vue.component('child', {
props: ['myMessage'],
template: '<mark>{{ myMessage }}<mark/>'
});
new Vue({
el: '#app1'
})
</script>

父子之間傳送數(shù)據(jù)

<div id="app2">
<input v-model="parentMsg">


<child :parent-msg="parentMsg"></child>
</div>
<script>
Vue.component('child', {
props: ['parentMsg'],
template: '<mark>{{ parentMsg }}<mark/>'
});
new Vue({
el: '#app2',
data: {
parentMsg: 'msg from parent!'
}
})
</script>

如果數(shù)據(jù)是引用對(duì)象則可以互傳

props: ['initialCounter'],
data: function () {
return { counter: this.initialCounter }
}
//定義一個(gè)局部computed屬性,此屬性從 prop 的值計(jì)算得出
props: ['size'],
computed: {
normalizedSize: function () {
return this.size.trim().toLowerCase()
}
}

子子傳數(shù)據(jù)

$emit $on

<div id="app3">
<p>Look at the parent's data: <mark>{{t}}</mark> & the child's data: <mark>{{childWords}}</mark></p>
<child v-on:add="pChange"></child>
<child v-on:add="pChange"></child>
<child v-on:click.native="native"></child>
</div>
<script>
Vue.component('child', {
template: <button @click="add">{{ c }}</button>,
data: function () {
return {
c: 0,
msg: 'I am from child's data'
}
},
methods: {
add: function () {
this.c += 1;
this.$emit('add',this.msg);
}
},
});
new Vue({
el: '#app3',
data: {
t: 0,
childWords: ''
},
methods: {
pChange: function (msg) {
this.t += 1;
this.childWords=msg;
},
native:function () {
alert('I am a native event ,which comes from the root element!');
}
}
})
</script>

<div id="app4">
<display></display>
<increment></increment>
</div>
<script>
var bus = new Vue();
Vue.component('increment', {
template: <button @click="add">+</button>,
data: function () {
return {count: 0}
},
methods: {
add: function () {
bus.$emit('inc', this.count+=1)
}
}
});
Vue.component('display', {
template: <span>Clicked: <mark>{{c}}</mark> times</span>,
data: function () {
return {c: 0}
},
created: function () {
var self=this;
// bus.$on('inc', function (num) {
// self.c = num
// });
bus.$on('inc', (num) =>
this.c = num
);
}
});
vm = new Vue({
el: "#app4",
})
</script>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容