vuex

注意:在ajax和axios中,使用store或route或router等全局变量时,注意this

- state和mutations的关系可以不严谨的理解成:

  - state(存储数据)

  - mutations(更改state数据的唯一方法)

  - 数据(state)  --------> view   -------> mutations()    ------> 数据(state)

      -         驱动        触发方法(绑定事件)       修改数据

一、作用

各个组件共享数据

二、过程

1、安装

npm install vuex --save

2、创建store文件夹->创建store.js文件

3、导入并引用

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

4、提供一个初始 state 对象和一些 mutation

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

5、在mian.js中导入,并注册

目的:store可以作为全局变量,通过this.$store.state.变量名 调用

import store from './store/store'

 6、mutations中的方法通过下面的方式触发

this.$store.commit('increment')

待参数

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

触发

this.$store.commit('increment',10)

7、例子

原文地址:https://www.cnblogs.com/wt7018/p/11538333.html