vue中使用vuex


首先是vuex的安装

1
npm install vuex --save

引入并引用vuex

1
2
3
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

创建store.js

1
2
3
4
5
6
7
8
9
10
const store = new Vuex.Store({
  state: {
    count0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

现在,你可以通过 store.state 来获取状态对象,以及通过 store.commit 方法触发状态变更:

1
store.commit('increment')

引用store的两种方式,在组件中引用

1
2
// 在组件中引用
import store from 'store'

通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到。

1
2
3
4
5
6
7
8
9
10
const app = new Vue({
  el'#app',
  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,
  components: { Counter },
  template`
    <div class="app">
      <counter></counter>
    </div>
`})

mapState 辅助函数

当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 在单独构建的版本中辅助函数为 
Vuex.mapStateimport { mapState } from 'vuex'
export default {
  // ...
  computedmapState({
    // 箭头函数可使代码更简练
    countstate => state.count,

    // 传字符串参数 'count' 等同于 `state => state.count`
    countAlias'count',

    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
      return state.count + this.localCount    
    }
  })
}