安裝:
npm i vuex
調試vuex的谷歌插件
vue.js devtools
新建文件store/index.js
import vuex from 'vuex'; import Vue from 'vue';
import channels from "./channels"; //1.安裝 Vue.use(vuex) var store = new vuex.Store({ //倉庫對象 //2.配置 modules:{
channels
} }) export default store;
使用:main.js
import store form './store' new Vue({ store })
新建:store/channels.js 如何改動倉庫數據(改動數據必須提教mutation)
export default {
namespaced: true,//開啟命名空間 state:{ data: [], isLoading: false, }
mutation:{
//state :原來的狀態
//payload: 負荷 需要傳的值
setIsLoading(state,payload)
state.isLoading = payload
},
setData(state,payload){
state,data = payload
}
actions:{ //有副作用的操作一部操作
async fetchDate(context){
//設置isLoading為true
context.commmit("setIsLoading",true)
var channels = await getxxx()
context.commit('setData',channels)
coontext.commit("setIsLoading",false)
}
} }
組件:login.vue
如何在組件中使用store中的數據 及 更改
第一種寫法獲取store屬性:
<templet> </templet> <script> export default{ computed:{ isLoading(){ return this.$store.state.channels.isLoading } } } </script>
第二種輔助函數
<templet> </templet> <script> import {mapState} from 'vuex' export default{ computed:mapStete('channels',['data','isLoading']) //channnels 為命名空間的名字,數組為讀取屬性 create的(){
this.$store.commit('channels/setIsLoading',true) //提交一個mutation
}
} </script> 注釋: 如果還有其他計算屬性(es6屬性展開運算符) computed:{ ...mapStete('channels',['data','isLoading']) , data(){ return 123 } }
例:
var obj = {
a:1,
b:2,
} var newObj = {
...obj,
c:3
}
輸出結果為{a:1,b:2,c:3}