實現(xiàn)vuex與組件data之間的數(shù)據(jù)同步更新方式
問題
我們都知道,在Vue組件中,data部分的數(shù)據(jù)與視圖之間是可以同步更新的,假如我們更新了data中的數(shù)據(jù),那么視圖上的數(shù)據(jù)就會被同步更新,這就是Vue所謂的數(shù)據(jù)驅(qū)動視圖思想。
當(dāng)我們使用Vuex時,我們也可以通過在視圖上通過 $store.state.[DataKey] 來獲取Vuex中 state 的數(shù)據(jù),且當(dāng) state 中的數(shù)據(jù)發(fā)生變化時,視圖上的數(shù)據(jù)也是可以同步更新的,這似乎看起來很順利。
但是當(dāng)我們想要通過將 state 中的數(shù)據(jù)綁定到Vue組件的 data 上,然后再在視圖上去調(diào)用 data ,如下:
<template>
<div>{{userInfo}}</div>
</template>
<script>
export default {
data() {
return {
userInfo: this.$store.state.userInfo;
};
}
};
</script>
那么我們就會發(fā)現(xiàn),當(dāng)我們?nèi)ジ淖?state 中的 userInfo 時,視圖是不會更新的,相對應(yīng)的 data 中的 userInfo 也不會被更改,因為這種調(diào)用方式是非常規(guī)的。
當(dāng)Vue在組件加載完畢前,會將 data 中的所有數(shù)據(jù)初始化完畢,之后便只會被動改變數(shù)據(jù)。然而等組件數(shù)據(jù)初始化完畢之后,即使 state 中的數(shù)據(jù)發(fā)生了改變, data 中的數(shù)據(jù)與其并非存在綁定關(guān)系,data 僅僅在數(shù)據(jù)初始化階段去調(diào)用了 state 中的數(shù)據(jù),所以 data 中的數(shù)據(jù)并不會根據(jù) state 中的數(shù)據(jù)發(fā)生改變而改變。
所以如果想在視圖上實現(xiàn)與 state 中的數(shù)據(jù)保持同步更新的話,只能采用以下方式:
<template>
<div>{{$store.state.userInfo}}</div>
</template>
解決
那么如果我們必須想要在 data 上綁定 state 中的數(shù)據(jù),讓 state 去驅(qū)動 data 發(fā)生改變,那我們該如何做呢?
我們可以嘗試以下兩中方法:
1. 使用computed屬性去獲取state中的數(shù)據(jù)
這種方式其實并非是去調(diào)用了 data 中的數(shù)據(jù),而是為組件添加了一個計算 computed 屬性。computed 通常用于復(fù)雜數(shù)據(jù)的計算,它實際上是一個函數(shù),在函數(shù)內(nèi)部進行預(yù)算后,返回一個運算結(jié)果,同時它有一個重要的特性:當(dāng)在它內(nèi)部需要進行預(yù)算的數(shù)據(jù)發(fā)生改變后,它重新進行數(shù)據(jù)運算并返回結(jié)果。 所以,我們可以用 computed 去返回 state 中的數(shù)據(jù),當(dāng) state 中的數(shù)據(jù)發(fā)生改變后,computed 會感知到,并重新獲取 state 中的數(shù)據(jù),并返回新的值。
<template>
<div>{{userInfo}}</div>
</template>
<script>
export default {
computed: {
userInfo(){
return this.$store.state.userInfo;
}
}
};
</script>
2. 使用watch監(jiān)聽state中的數(shù)據(jù)
這種方式就很好理解了,就是通過組件的 watch 屬性,為 state 中的某一項數(shù)據(jù)添加一個監(jiān)聽,當(dāng)數(shù)據(jù)發(fā)生改變的時候觸發(fā)監(jiān)聽事件,在監(jiān)聽事件內(nèi)部中去更改 data 中對應(yīng)的數(shù)據(jù),即可變相的讓 data 中的數(shù)據(jù)去根據(jù) state 中的數(shù)據(jù)發(fā)生改變而改變。
<template>
<div>{{userInfo}}</div>
</template>
<script>
export default {
data() {
return {
userInfo: this.$store.state.userInfo;
};
},
watch: {
"this.$store.state.userInfo"() {
this.userInfo = this.$store.getters.getUserInfo; // 按照規(guī)范在這里應(yīng)該去使用getters來獲取數(shù)據(jù)
}
}
};
</script>
以上這篇實現(xiàn)vuex與組件data之間的數(shù)據(jù)同步更新方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue彈窗組件的使用(傳值),以及彈窗只能觸發(fā)一次的問題
這篇文章主要介紹了vue彈窗組件的使用(傳值),以及彈窗只能觸發(fā)一次的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
Vue中使用this.$set()如何新增數(shù)據(jù),更新視圖
這篇文章主要介紹了Vue中使用this.$set()實現(xiàn)新增數(shù)據(jù),更新視圖方式。具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06

