1.png
如果看懂這張圖片那就說明你就會用了
以上是vuex使用流程圖 用于多個組件數(shù)據(jù)傳值烂翰,公用數(shù)據(jù)放到公用的存儲空間蛇耀,某一個組件改變了公用數(shù)據(jù)其他組件可以感知到
公用數(shù)據(jù)是存放在state里面
改變state中的公用數(shù)據(jù)流程:
1、如果是異步操作或者復(fù)雜的批量同步操作就放到actions(組件使用dispatch調(diào)用actions)里面--->調(diào)用mutations(actions使用commit調(diào)用mutations)浦旱,里面放的是一個個同步對state的修改身腻;
2、也可以濾過actions直接調(diào)用mutations改變state里面的值砖瞧,當(dāng)數(shù)據(jù)發(fā)生變化時組件展示也發(fā)生了
在main里面引入,放到Vue根實例下嚷狞,這樣所有的頁面都可以直接使用
changCity方法名字可以自定義
ctx為上下文块促,這樣可以拿到commit方法
2.png
在組件里調(diào)用改變
3.png
以上通過actions轉(zhuǎn)發(fā)調(diào)用mutations改變state數(shù)據(jù)的
以下是直接調(diào)用mutations改變state數(shù)據(jù)
使用localStorage做數(shù)據(jù)緩存
4.png
使用try catch做優(yōu)化
5.png
6.png
實際開發(fā)中簡化寫法 把state、actions床未、mutations分別定義一個js文件 在store文件中引入
7.png
import {mapState,mapMutations} from 'vuex' 的使用
//調(diào)用
//可以簡化寫法
<div class="button">
<!--{{this.$store.state.city}}-->
{{this.currentCity}}
</div>
/*數(shù)組寫法
computed: {
//mapState是值把vuex里的數(shù)據(jù)映射到該組件的計算屬性里
// 就是把city映射到了computed的city計算屬性中
...mapState(['city'])
}
*/
computed: {
//mapState可以是數(shù)組也可以是對象
//下列意思是 把vuex里的city映射到組件的計算屬性里
//映射過來的名字就是currentCity
...mapState({
currentCity: 'city'
})
},
methods: {
handleBtnClick(value){
//派發(fā)一個叫changeValue的方法傳遞的參數(shù)是value
//常規(guī)使用 修改state 通過actions再調(diào)用mutations
//this.$store.dispatch('changeValue',value)
//直接調(diào)用mutations寫法
// this.$store.commit('changeCity', value)
//mapMutations的寫法
this.changeCity(value)
this.$router.push('/')
},
//mutations中有一個changeCity
//把mutations中的changeCity映射到組件的叫做changeCity的方法里
...mapMutations(['changeCity'])
}
getters用法
getters的作用類似于組件中的computed計算屬性的作用竭翠,
當(dāng)我們想根據(jù)state里的數(shù)據(jù)算出新的數(shù)據(jù)的時候,可以使用getters提供新的數(shù)據(jù)薇搁,避免冗余
8.png
9.png