實(shí)現(xiàn)vuex與組件data之間的數(shù)據(jù)同步更新方式

原文鏈接:https://blog.csdn.net/u012925833/java/article/details/90264152
錯(cuò)誤方式

<template>
 <div>{{userInfo}}</div> 
</template>
 
<script>
export default {
 data() {
 return {
  userInfo: this.$store.state.userInfo;
 };
 }
};
</script>

這種方式不能實(shí)現(xiàn)state中的數(shù)據(jù)與template中的數(shù)據(jù)實(shí)時(shí)更新
因?yàn)閟tate中的數(shù)據(jù)與data中的數(shù)據(jù)不存在綁定關(guān)系,所以vue組件初始化完畢后,若state中的數(shù)據(jù)發(fā)生改變,data中的數(shù)據(jù)不能監(jiān)聽(tīng)到,不能重新給他賦值


mustache
直接在mustache中使用state中的數(shù)據(jù)

<template>
 <div>{{$store.state.userInfo}}</div> 
</template>

通過(guò)computed屬性
computed 屬性中的方法中依賴的數(shù)據(jù)發(fā)生改變的時(shí)候,方法就會(huì)重新計(jì)算并返回結(jié)果

<template>
 <div>{{userInfo}}</div> 
</template>

<script>
export default {
  computed: {
    userInfo(){
          return this.$store.state.userInfo
       }
    }
 };
</script>

通過(guò)watch監(jiān)聽(tīng)state中的屬性
這種方式就很好理解了,就是通過(guò)組件的 watch 屬性,為 state 中的某一項(xiàng)數(shù)據(jù)添加一個(gè)監(jiān)聽(tīng),當(dāng)數(shù)據(jù)發(fā)生改變的時(shí)候觸發(fā)監(jiān)聽(tīng)事件,在監(jiān)聽(tīng)事件內(nèi)部中去更改 data 中對(duì)應(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來(lái)獲取數(shù)據(jù)
    }
  }
};
</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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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