Vue組件之間數(shù)據(jù)共享淺析
組件數(shù)據(jù)共享
組件之間的關(guān)系:在項目開發(fā)中,組件之間的最常用的關(guān)系分為兩種:父子關(guān)系和兄弟關(guān)系。
父組件向子組件共享數(shù)據(jù)
通過自定義屬性實現(xiàn)父向子傳值。


子組件向父組件共享數(shù)據(jù)
通過自定義事件實現(xiàn)子向父傳值


兄弟組件共享數(shù)據(jù)
在 vue2.x中,兄弟組件之間數(shù)據(jù)共享方案是 EventBus。
EventBus的使用步驟:
1)創(chuàng)建eventBus.js模塊,并向外共享一個Vue的實例對象
import Vue from 'vue' // 向外共享 Vue 的實例對象 export default new Vue()
2)在數(shù)據(jù)發(fā)送方,調(diào)用bus.$emit('事件名稱',要發(fā)送的數(shù)據(jù))方法觸發(fā)自定義事件
<template>
<div class="left-container">
<h3>Left組件--{{count}}</h3>
<button @click="send">點擊給Right發(fā)送數(shù)據(jù)</button>
</div>
</template>
<script>
// 1.導(dǎo)入 eventBus.js 模塊
import bus from './eventBus'
export default{
data(){
return {
// 兄弟組件要傳送的數(shù)據(jù)
str:'我想對你說:hello world'
}
},
methods:{
send(){
// 2.通過eventBus來發(fā)送數(shù)據(jù)
bus.$emit('share',this.str)
}
}
}
</script>
<style lang="less" scoped>
h3{
color: #f00;
}
.left-container{
padding: 0 20px 20px;
background-color: orange;
min-height: 250px;
flex: 1;
}
::v-deep h5{
color:#00f
}
</style>3)在數(shù)據(jù)接受方,調(diào)用bus.$on('事件名稱',事件處理函數(shù))方法注冊一個自定義事件
<template>
<div class="right-container">
<h3>Right組件</h3>
{{msgFromLeft}}
</div>
</template>
<script>
// 1.導(dǎo)入 eventBus.js 模塊
import bus from './eventBus'
export default{
data(){
return {
// 兄弟組件要接受的數(shù)據(jù)
msgFromLeft:""
}
},
created(){
bus.$on('share',val=>{
this.msgFromLeft = val
// console.log('在Right組件中定義的share被觸發(fā)了!',val);
})
}
}
</script>
<style>
.right-container{
padding: 0 20px 20px;
background-color: orange;
min-height: 250px;
flex: 1;
}
</style>
到此這篇關(guān)于Vue組件之間數(shù)據(jù)共享淺析的文章就介紹到這了,更多相關(guān)Vue組件數(shù)據(jù)共享內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue服務(wù)端渲染和Vue瀏覽器端渲染的性能對比(實例PK )
這篇文章主要介紹了Vue服務(wù)端渲染和Vue瀏覽器端渲染的性能對比(實例PK ),非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-03-03
前端實現(xiàn)pdf預(yù)覽功能的全過程(基于vue)
這篇文章主要給大家介紹了關(guān)于前端實現(xiàn)pdf預(yù)覽功能的相關(guān)資料,前端實現(xiàn)預(yù)覽最好的效果還是PDF,不會出現(xiàn)一些文字錯亂和亂碼的問題,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-09-09

