一:store:vueX的核心
我們可以將store認為是一個倉庫,這個倉庫中保存着組件之間共享的數據 state和方法
1,state
在store中存在這state,這里面保存着所有組件之間共享的數據:這里面的狀態是響應式的,如果store中的狀態得到變化,那么相應的組件的狀態也會得到變化;
2,mutations
我們通過mutations來實現改變store中的state
我們通過 store.state來獲取狀態對象,我們通過 store.commit來觸發狀態更新
二:讀取store對象:
我們如何讀取store對象呢?
在store實例中讀取狀態的方法是在計算屬性中返回某個狀態;
代碼如下:
const Counter = { template: `<div>{{ count }}</div>`, computed: { count () { return this.$store.state.count } } }
我們在根實例中注入store對象,然后在子組件中通過 this.$store來訪問到:
this.$store.state來訪問到狀態;
但是這種方法只能獲取一種狀態,但我們需要獲取到多種狀態的時候,我們通過 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 } }) }
如上:
三:getters:
getters是用於計算state的函數,這實際上是函數,使用這個函數我們可以對state進行處理:
代碼如下:
const store = new Vuex.Store({ state: { todos: [ { id: 1, text: '...', done: true }, { id: 2, text: '...', done: false } ] }, getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) } } })
如上:
這段代碼的意思是 對於state中的todos進行處理:
調用:
store.getters.doneTodos
或者在組件中調用:
computed: { doneTodosCount () { return this.$store.getters.doneTodos } }
如上:
mapGetters用於將store中的getters映射到局部屬性:
import { mapGetters } from 'vuex' export default { // ... computed: { // 使用對象展開運算符將 getters 混入 computed 對象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) } }
完: