vuex 其实跟 vue 非常像,有data(state),methods(mutations,actions),computed(getters),还能模块化.

第零步
新建一个vue项目,安装vuex,这里不做过多介绍,能点进来的,默认你具备这些技能
第一步
新建一个.js 文件,名字位置任意,按照惯例,建议在/src/store 目录下(没有的话自己新建一个呗)
文件位置 /src/store/index.js

// 引入vue 和 vuex
import Vue from 'vue'
import Vuex from 'vuex'

// 这里需要use一下,固定写法,记住即可
Vue.use(Vuex)

// 直接导出 一个 Store 的实例
export default new Vuex.Store({
  // 类似 vue 的 data
  state: {
    name: 'oldName'
  },
  // 类似 vue 里的 mothods(同步方法)
  mutations: {
    updateName (state) {
      state.name = 'newName'
    }
  }
})

代码看起来稍微有那么一点点多,不过看起来是不是很熟悉? 跟普通的 vue 没多大差别嘛. 这一步其实就是新建一个store,但是我们还没在项目中使用.

第二步

在入口文件引入上述文件, 并稍微改一下传给 new Vue()的参数,新增的行后面有备注
文件位置 /src/main.js (vue-cli自动生成的入口,如果你能不用脚手架,那么也就不需要我说明了)

import Vue from 'vue'
import App from './App'
import vuexStore from './store'   // 新增

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

Tip: import store from ‘./store’ 后面的地址,就是上面我们新建那个文件的位置(/src/store/index.js), 因为我这里是index.js,所以可以省略.

第三步

以上2步,其实已经完成了vuex的基本配置,接下来就是使用了
文件位置 /src/main.js (同样是vue-cli生成的app.vue,这里为了方便演示,我去掉多余的代码)

<template>
  <div>
    {{getName}}
    <button @click="changeName" value="更名">更名</button>
  </div>
</template>

<script>
export default {
  computed:{
    getName(){
      return this.$store.state.name
    }
  },
  methods:{
    changeName () {
      this.$store.commit('updateName')
    }
  }
}
</script>

这里就是一个很普通的vue文件了,有区别的地方是这里我们需要用computed属性去获取 store 里的 “data”

还有就是我们要改变数据的话,不再用 this.xxx = xxx 改成 this.$store.commit(‘updateName’)

总结

你可能会觉得,上例这样做的意义何在,为何不直接用vue的data跟methods?

上例只是为了简单讲解如何使用vuex,所以简化了一些流程,试想一下,如果你有这样一个页面: 一共嵌套了10层组件(即子组件里面还有子子组件,子子组件下面还有子子子组件,以此类推10层) 然后最后一层组件一个数据改变了,要通知第一层组件的时候,我们只需在最底层组件里this. s t o r e . c o m m i t ( ) , c o m p u t e d , . emit上去.

vuex其实超简单,喝完这3步,还有3步

一、 Getter

我们先回忆一下上一篇的代码

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

这里假设现在逻辑有变,我们最终期望得到的数据(getName),是基于 this.$store.state.name
上经过复杂计算得来的,刚好这个getName要在好多个地方使用,那么我们就得复制好几份.
vuex 给我们提供了 getter,请看代码 (文件位置 /src/store/index.js)

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  // 类似 vue 的 data
  state: {
    name: 'oldName'
  },
  // 类似 vue 的 computed -----------------以下5行为新增
  getters:{
    getReverseName: state => {
        return state.name.split('').reverse().join('')
    }
  },
  // 类似 vue 里的 mothods(同步方法)
  mutations: {
    updateName (state) {
      state.name = 'newName'
    }
  }
})

然后我们可以这样用 文件位置 /src/main.js

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

事实上, getter 不止单单起到封装的作用,它还跟vue的computed属性一样,会缓存结果数据,
只有当依赖改变的时候,才要重新计算.

二、 actions和$dispatch

细心的你,一定发现我之前代码里 mutations 头上的注释了 类似 vue 里的 mothods(同步方法)
为什么要在 methods 后面备注是同步方法呢? mutation只能是同步的函数,只能是同步的函数,只能是同步的函数!!
请看vuex的解释:

现在想象,我们正在 debug 一个 app 并且观察 devtool 中的 mutation 日志。每一条 mutation 被记录,
devtools 都需要捕捉到前一状态和后一状态的快照。然而,在上面的例子中 mutation 中的异步函数中的回调让这不
可能完成:因为当 mutation 触发的时候,回调函数还没有被调用,devtools 不知道什么时候回调函数实际上被调
用——实质上任何在回调函数中进行的状态的改变都是不可追踪的。

那么如果我们想触发一个异步的操作呢? 答案是: action + $dispatch, 我们继续修改store/index.js下面的代码
文件位置 /src/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  // 类似 vue 的 data
  state: {
    name: 'oldName'
  },
  // 类似 vue 的 computed
  getters:{
    getReverseName: state => {
        return state.name.split('').reverse().join('')
    }
  },
  // 类似 vue 里的 mothods(同步方法)
  mutations: {
    updateName (state) {
      state.name = 'newName'
    }
  },
  // 类似 vue 里的 mothods(异步方法) -------- 以下7行为新增
  actions: {
    updateNameAsync ({ commit }) {
      setTimeout(() => {
        commit('updateName')
      }, 1000)
    }
  }
})

然后我们可以再我们的vue页面里面这样使用

methods: {
    rename () {
        this.$store.dispatch('updateNameAsync')
    }
}

三、 Module 模块化

当项目越来越大的时候,单个 store 文件,肯定不是我们想要的, 所以就有了模块化. 假设 src/store 目录下有这2个文件

moduleA.js

export default {
    state: { ... },
    getters: { ... },
    mutations: { ... },
    actions: { ... }
}

moduleB.js

export default {
    state: { ... },
    getters: { ... },
    mutations: { ... },
    actions: { ... }
}

那么我们可以把 index.js 改成这样

import moduleA from './moduleA'
import moduleB from './moduleB'

export default new Vuex.Store({
    modules: {
        moduleA,
        moduleB
    }
})

这样我们就可以很轻松的把一个store拆分成多个.

四、 总结

actions 的参数是 store 对象,而 getters 和 mutations 的参数是 state .
actions 和 mutations 还可以传第二个参数,具体看vuex官方文档
getters/mutations/actions 都有对应的map,如: mapGetters , 具体看vuex官方文档
模块内部如果怕有命名冲突的话,可以使用命名空间, 具体看vuex官方文档
vuex 其实跟 vue 非常像,有data(state),methods(mutations,actions),computed(getters),还能模块化.

猜你喜欢

转载自blog.csdn.net/qq_29132907/article/details/80496092