文章82
标签28
分类8

Vuex的简单使用

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

  
Vuex 并不限制你的代码结构。但是,它规定了一些需要遵守的规则:

  • 应用层级的状态应该集中到单个 store 对象中。

  • 提交 mutation 是更改状态的唯一方法,并且这个过程是同步的。

  • 异步逻辑都应该封装到 action 里面。

核心概念

  • State:存放公有的数据

  • Getter:类似于计算属性

  • Mutation:对数据同步的改变

  • Action:异步的方法

安装 Vuex

npm install vuex --save

实例化一个 Vuex

  • 新建一个文件夹 store ,创建一个 index.js 的文件,实例化 Vuex
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  // 这里写数据的初始状态,类似于 data
  },
  mutations: {
  // 更改变化,类似于 methods, 同步执行
  },
  getters: {
  // 计算属性,类似于computed
  },
  actions: {
  // 类似于 mutations, 不过是异步操作的
  }
})
  • 然后在 mian.js 中使用此文件
// 引入 vuex
import store from './store'

new Vue({
  el: '#app',
  store,
  components: { App },
  template: '<App/>'
})

如何使用

  • state
// 直接在组件内使用
this.$store.state.count
// 通过映射的方式
import {mapState} from 'vuex'

export default {
    computed: {
        ...mapState({
          todolist: state => state.todolist
        })
    }
}
  • mutations
// 直接在组件内使用
this.$store.commit('方法名称', 参数)
// 通过映射的方式
import { mapMutations } from 'vuex'

...mapMutations([
  'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

  // `mapMutations` 也支持载荷:
  'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
])
  • getters
// 在组件中直接使用
this.$store.getters.doneTodosCount
// 通过映射的方式
import { mapGetters } from 'vuex'
computed: {
    // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
}