原文鏈接: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>