Vuex

233 阅读1分钟

0、vuex使用Module

// store
const moduleA = {
  namespaced: true, //使用命名空间
  state: { ... },
  getters: { ... },
  mutations: { ... },
  actions: { ... }
}
const moduleB = {
  state: { ... },
  getters: { ... }, //模块内部的 getter,根节点状态会作为第三个参数暴露出来:(state, getters, rootState)
  mutations: { ... },
  actions: { ... } //actions内获取根节点状态:context.rootState
  //** 命名空间模块可以注册全局action
    actions: {
        someAction: {
            root: true, //全局
            handler (namespacedContext, payload) { ... } // -> 'someAction'
        }
    }
}
const store = new Vuex.Store({
  modules: {
    moduleA,
    moduleB
  }
})
//命名空间
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapActions } = createNamespacedHelpers('some/nested/module') // 创建基于某个命名空间辅助函数
  • 在 store 创建之后,你可以使用 store.registerModule 方法注册模块。

1、state

// 获取某个store
computed: {
    count () {
        return store.state.count
    }
}
// 获取多个store
import { mapState } from 'vuex'
computed: mapState({
    count: state => state.count,
    countAlias: 'count',  // 传字符串参数 'count' 等同于 `state => state.count`
    'count', // 映射 this.count 为 store.state.count
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
})
// store 与state computed 混合
computed: {
  localComputed(){},
  ...mapState({
    // ...
  })
}

2、getter (store 的计算属性)

//定义
getters: {
    doneTodos: (state, getters) => {
        return state.todos.filter(todo => todo.done)
    },
    getTodoById: (state) => (id) => { //接收传参
        return state.todos.find(todo => todo.id === id)
    }
}
// 获取
store.getters.doneTodos //store内
computed: { 
  doneTodosCount () {
    return this.$store.getters.doneTodosCount //组件中
  }
}
//辅助函数
import { mapGetters } from 'vuex'
computed: {
    ...mapGetters([
       'doneTodosCount', //doneTodosCount: this.$store.getters.doneTodosCount
       'anotherGetter',
    ])
  }

3、Mutation (更改store状态的唯一方法)

//注册
mutations: {
  increment (state, payload) {
    state.count = payload.count
  }
}
//调用
store.commit('increment', {count: 10})
store.commit({ type: 'increment', amount: 10 })
//辅助函数
import { mapMutations } from 'vuex'
methods: {
    ...mapMutations([
      'increment', // increment(){  this.$store.commit('increment'); }
      'incrementBy' //传参时incrementBy(amount){ this.$store.commit('incrementBy', amount) }
    ])
  }

4、 Action (提交mutation)

//注册
actions: {
    increment (context) { //简写 {dispatch, commit,state, getters}
        const state = context.state; //获取状态
        const s = context.getters; //获取getters
        context.commit('increment')
        return new Promise((resolve, reject)=>{
            //...
        });
    }
 }
 //调用
 store.dispatch('increment', {amount: 10})
 store.dispatch({ type: 'incrementAsync', amount: 10 })
 //辅助函数
 import { mapActions } from 'vuex'
 methods: {
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ])
  }

常用技巧

//双向数据绑定
<input v-model="message">

computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
}