vuex快速复习及易忽略知识

26 阅读1分钟

安装挂载

  • 注意,虽然import xx from 'store.js' 实际执行时会把store.js文件执行一遍,并找到export匹配的项导出
----store.js-------
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

export default store
------main.js-----------
import store from './store.js'
new Vue({
  el: '#app',
  // 这样 后面可以通过this.$store访问new Vuex.Store创建出来的实例
  store
})

state

一般使用(通过computed)this.$store.state

 computed: {
    count () {
      return this.$store.state.count
    }

mapState

import { mapState } from 'vuex'
export default {
    computed: {
      calcWidth () { xxx  return xxx },
      // 使用对象展开运算符将此对象混入到外部对象中
      ...mapState(['count'])
    }
}

getters

-------store.js-----------
 getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }

一般使用(通过computed) this.$store.getters

computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}

mapGetters

import { mapGetters } from 'vuex'

 computed: {
 // 使用对象展开运算符将 getter 混入 computed 对象中
   ...mapGetters([
     'doneTodosCount',
     'anotherGetter',
     // ...
   ])
 }

mutations

mutations: {
  increment (state, n) {
    state.count += n
  }
}

一般用法(methods)

  • 常常只作为methods的一部分this.$store.commit
 methods: {
    doSomeThing(){
        this.$store.commit('increment')
    }
 }

mapMutations

import { mapMutations } from 'vuex'
 methods: {
    ...mapMutations(['increment'])
 }

actions

  • 默认返回promise,且返回值resolve为undefined
  • actions里明确return一个promise,则resolve以return的为准
----- store.js---------
  actions: {
    asyncFuc() {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve("异步函数调用");
        }, 3000);
      });
    },
  },
--------.vue---------
methods:{
 dosomething(){
  // 会等异步执行完成后 执行then
  this.$store.dispatch('asyncFuc').then((el) => {
    console.log(`${el}-异步`)
  })
 }
}

一般用法 (methods)

  • 方法里包含 this.$store.dispatch
methods:{
    doSomething(){
        this.$store.dispatch('incrementAsync')
    }
}

mapActions

import { mapActions } from 'vuex'

 methods: {
     ...mapActions([      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`    ]),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
 }

modules命名空间

  • 模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。只有state是私有空间
  • 通过添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。