1、vuex是什麼:Vuex 是一個專爲 Vue.js 應用程序開發的狀態管理模式。它採用集中式存儲管理應用的所有組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。
2、學習準備:
1)、vuex中文官網
2)、搭建好vue腳手架,vue init webpack <projectName> 文件名不建議使用‘vuex’,因爲創建好腳手架後使用vuex需要進行npm安裝。這個時候會檢測到你使用的項目名Name爲:”vuex“,然後報錯,網上有一個這個問題,如果遇到可移步;
3)、安裝vuex:
npm install vuex --save
yarn add vuex
3、使用:
1)、在vuecli目錄下創建一個store目錄並新建一個index.js文件。以下是index.js文件內容
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state:{ count: 0, cityName: "北京", todos: [ { id: 1, text: '...', done: true }, { id: 2, text: '...', done: false } ] } }) export default store
2)、引入存儲並注入
在main.js中引入我們剛剛創建的index.js文件:
import store from './store/index.js'
並且注入存儲:new Vue({
store,
render: h => h(App)
}).$mount('#app-box')
3)、使用測試
State
在vue頁面中進行測試使用,檢驗是否能獲取到store中的參數
在methods中隨便寫一個方法,進行訪問(通過屬性訪問)
console.log(this.$store.state.cityName);
console.log(this.$store.state.todos.length);
也可以在computed中直接通過一下進行訪問並渲染到頁面中
computed: {
cityName() {
return this.$store.getters.cityname;
}
}
在html中書寫:<span @click="changeCity">{{cityName}}</span>
Getter
有時候我們需要從 store 中的 state 中派生出一些狀態,例如對列表進行過濾等;我們可以在 store 中定義“getter”(可以認爲是 store 的計算屬性)。就像計算屬性一樣,getter 的返回值會根據它的依賴被緩存起來,且只有當它的依賴值發生了改變纔會被重新計算。例如: // vue頁面中調用一下方法獲取return的值
getters: {
cityname(state) {
return state.cityName + "市區"
},
upperOwner(state) {
return state.owner.slice(0, 1).toUpperCase() + state.owner.slice(1)
},
doneTodos(state) {
return state.todos.filter(a => a.done == true) //獲取到done爲true的元素
},
getTodoById: (state) => (id) => {
return state.todos.filter(a => a.id == id) //獲取到id爲指定id的元素
}
},
vue頁面中調用getters方法的兩種方式:
屬性訪問:
console.log(this.$store.getters.doneTodos);
方法訪問(紅色字store需要先進行導入:“import store from "../store/index.js";")):
console.log(store.getters.getTodoById(2)) //獲取到id爲指定id的元素
mutation
store.commit
傳入額外的參數,即 mutation 的 載荷(payload): mutations: {
// 函數參數1 state:state狀態
// 函數參數2 自定義參數
// 必須是同步函數
getCityName(state, newVal) {
state.cityName = newVal
console.log(state.cityName)
}
},
vue頁面中調用 store.commit 方法進行提交mutationstore.commit("getCityName", "北京");
Action
Action 類似於 mutation,不同在於:
- Action 提交的是 mutation,而不是直接變更狀態。
- Action 可以包含任意異步操作。
actions: {
// context 上下文 只帶當前store對象
// param 參數
getCityName(context,param){
setTimeout(function(){
// 修改state 依舊需要提交mutations 纔可以改變
context.commit('getCityName',param)
}, 1000);
}
}
vue頁面中調用:在組件中使用 this.$store.dispatch('xxx')
分發 action
setTimeout(() => {
this.$store.dispatch("getCityName", 'action觸發');
}, 3000);
下面是主要代碼:
備註:state的mapState輔助函數,getter的mapGetters輔助函數,Mutation的mapMutations輔助函數此處沒有,可移步官網查看核心概念對應學習