vuex基本使用
創建一個 store
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count += 1 } }, actions: {}, modules: {} })
獲取state值
1. 在標簽中直接調用
<div>count: {{ $store.state.count }}</div>
2.通過計算屬性
<div>count: {{ count }}</div>
computed: {
count() {
return this.$store.state.count;
}
},
3.當一個組件需要多個狀態的時候,可以借助 mapState 輔助函數來實現
// 在單獨構建的版本中輔助函數為 Vuex.mapState import { mapState } from 'vuex' export default { // ... computed: mapState({ // 箭頭函數可使代碼更簡練 count: state => state.count, // 傳字符串參數 'count' 等同于 `state => state.count` countAlias: 'count', // 為了能夠使用 `this` 獲取局部狀態,必須使用常規函數 countPlusLocalState (state) { return state.count + this.localCount } }) }
4. 當映射的計算屬性的名稱與 state 的子節點名稱相同時,我們也可以給 mapState 傳一個字符串數組。
computed: mapState([ // 映射 this.count 為 store.state.count 'count' ])
5. 通過 對象展開運算符 實現
computed: { ...mapState(["count"]) },
Getters
getters可以當作是 store 的計算屬性,就像計算屬性一樣,getter 的返回值會根據它的依賴被緩存起來,且只有當它的依賴值發生了改變才會被重新計算。
store中state內容
state: { todos: [{ id: 1, text: '...', done: true }, { id: 2, text: '...', done: false } ] },
1. Getter 接受 state 作為其第一個參數
getters: { doneTodos: state => { return state.todos.filter(todo => todo.done)
} }, // 屬性訪問 store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
2.Getter 也可以接受 getters 作為第二個參數:
getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) }, doneTodosCount: (state, getters) => { return getters.doneTodos.length
} },
this.$store.getters.doneTodosCount; // 1, 通過屬性訪問
3.通過方法訪問
也可以通過讓 getter 返回一個函數,來實現給 getter 傳參。
getters: { // ... getTodoById: (state) => (id) => { return state.todos.find(todo => todo.id === id) } } store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
注意,getter 在通過方法訪問時,每次都會去進行調用,而不會緩存結果。
4. mapGetters 輔助函數訪問
computed: { // 使用對象展開運算符將 getter 混入 computed 對象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter', ]) } // 如果你想將一個 getter 屬性另取一個名字,使用對象形式: computed: { ...mapGetters({ // 把 `this.doneCount` 映射為 `this.$store.getters.doneTodosCount` doneCount: "doneTodosCount" }) },

浙公網安備 33010602011771號