vuex

94 阅读1分钟

白话vuex

核心:单一状态树:一个应用对应一个store。

快速了解vuex中的核心知识点

State

state:可以理解为data()里面的数据(通过this.$store.state调用)。Vuex 的状态存储是响应式的,所以可以在computed中去读取store中的状态。

const store = new Vuex.Store({
    state: {
        count: 0,
        size: 10,
    }
})
在组件中调用(假设已经注入到全局Vue.use(store))
computed: {
    count() {
        return this.$store.state.count
        }
}

以上是获取一个状态的方法,如果要获取多个状态可以通过辅助函数 mapState 来帮助我们生成计算属性,这样就不用去声明多个计算属性来获取多个状态。

// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
// mapState返回的是一个对象,为了和局部计算属性混合使用,所以使用对象展开运行算符
computed: {
    ...mapState({
        count: state => state.count,
        
         // 传字符串参数 'count' 等同于 `state => state.count`
        countAlias: 'count',
         // 为了能够使用 `this` 获取局部状态,必须使用常规函数
        countPlusLocalState(state) {
            return state.count + this.localCount
        }
    })
 }
 

当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。

 computed: mapState([
  // 映射 this.count 为 store.state.count
  'count'
])

getters

getters:可以理解为store的计算属性 如果我们要对store中的state属性做一些处理,就可以用到getters

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) 
        }
    }
})

如何访问getters,通过属性访问:

computed: {
    ...mapGetters([}

参考: Vuex官网