Vuex
簡介:vuex是vue.js的狀態(tài)管理庫
提供一種集中式存儲管理應(yīng)用程序中的所有組件的狀態(tài),并將其分離到一個可預(yù)測的狀態(tài)容器中。
五個核心屬性:state、mutations、actions、getters、modules
屬性 | 作用 |
---|---|
state |
存放狀態(tài) (數(shù)據(jù)),所有組件共享 |
mutations |
唯一可以修改state的地方,改變state狀態(tài) 需要通過顯示地commit(提交)mutation (同步) |
actions |
用于異步操作 和提交mutations ,根據(jù)后端接口返回數(shù)據(jù)去commit更新數(shù)據(jù)
|
getters |
獲取 state中的狀態(tài) |
modules |
將store分割成模塊 ,每個模塊都擁有自己的state、mutation、action、getters和子模塊,以便提高應(yīng)用程序的可維護(hù)性 |
兩個輔助函數(shù):mapState、mapGetters
屬性 | 作用 | 用法 |
---|---|---|
mapState |
將 store 中的 state 映射到局部計算屬性 | computed: {…mapState([‘count’, ‘xx’]),} |
mapGetters |
將 store 中的 getter 映射到局部計算屬性 | computed: {…mapGetters([‘count’, ‘xx’]),} |
當(dāng)一個組件需要獲取多個狀態(tài)的時候,可以使用 mapState或mapGetters 輔助函數(shù)幫助我們生成計算屬性,減少冗余代碼:文章來源:http://www.zghlxwxcb.cn/news/detail-535530.html
// store 中的 state、getter 映射到局部計算屬性
import { mapState, mapGetters } from 'vuex';
computed: {
// 使用對象展開運(yùn)算符將此對象混入到外部對象中
...mapState(['count']),
...mapGetters(['count']),
localComputed () { /* ... */ },
}
可以通過 this.$store
訪問store實(shí)例,從Store中讀取state
(狀態(tài)),改變state狀態(tài)需要通過顯示地commit
(提交)mutation
;文章來源地址http://www.zghlxwxcb.cn/news/detail-535530.html
//當(dāng)有modules模塊化時要注意提交commit需要加上文件名
this.$store.commit('app/SET_COUNT', 10)
到了這里,關(guān)于【VUEX】state、mutations、actions、getters、modules以及輔助函數(shù)mapState和mapGetters的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!