vuex 详解

先说一下vuex到底是什么?

vuex 是一个专门为vue.js应用程序开发的状态管理模式。
这个状态我们可以理解为在data中的属性,需要共享给其他组件使用的部分。

也就是说,是我们需要共享的data,使用vuex进行统一集中式的管理。

 

vuex中,有默认的五种基本的对象:

state:存储状态(变量)
getters:对数据获取之前的再次编译,可以理解为state的计算属性。我们在组件中使用 $sotre.getters.fun()
mutations:修改状态,并且是同步的。在组件中使用$store.commit('',params)。这个和我们组件中的自定义事件类似。
actions:异步操作。在组件中使用是$store.dispath('')
modules:store的子模块,为了开发大型项目,方便状态管理而使用的。这里我们就不解释了,用起来和上面的一样。
 

 

下面我们正式开始,一步步使用vuex

 

 

1、首先创建一个vue-cli项目

执行下面的命令,创建一个app项目(这里也可以使用其他非webpack模板,以及非app名称)

vue init webpack app


2、创建完成之后,我们进入文件夹下,并且运行项目

cd app/
npm run dev
接下来我们在src目录下创建一个vuex文件夹

并在vuex文件夹下创建一个store.js文件

文件夹目录长得是这个样子



 

3、目前我们还没有引入vuex,我们需要先下载vuex,并且引入它

在保证我们处于我们项目下,在命令行输入下面命令,安装vuex

npm install vuex --save


4、安装成功之后,我们就可以在store.js中尽情玩耍我们的vuex了!

在store.js文件中,引入vuex并且使用vuex,这里注意我的变量名是大写Vue和Vuex 

按 Ctrl+C 复制代码
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
    count: 0
}

export default new Vuex.Store({
    state
})
按 Ctrl+C 复制代码


接下来,在main.js中引入store

复制代码
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './vuex/store' // 引入store
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    store,
    components: { App },
    template: '<App/>'
})
复制代码
然我我们在任意一个组件中就可以使用我们定义的count属性了。

这里我们在helloWorld中使用一下,去除helloworld.vue中不用的标签

<template>
  <div class="hello">
    <h3>{{$store.state.count}}</h3>
  </div>
</template>
打开我们刚才运行项目的浏览器,可以看到已经使用成功了!



并且在vue开发工具中我们可以看到我们定义的变量count



到这一步,已经成功了一小半!vuex很简单吧?

回想一下,我们只需要在下载安装使用vuex,在我们定义的store.js中定义state对象,并且暴露出去。

在main.js中使用我们的store.js(这里是为了防止在各个组件中引用,因为main.js中,有我们的new Vue 实例啊!)

 

现在我们已经使用了vuex中的state,接下来我们如何操作这个值呢? 没错!用mutations和actions

我们继续操作store.js文件

我们在sotre.js中定义mutations对象,该对象中有两个方法,mutations里面的参数,第一个默认为state,接下来的为自定义参数。

我们在mutations中定义两个方法,增加和减少,并且设置一个参数n,默认值为0,然后在Vuex.Store中使用它

复制代码
/**
 * mutations 里面放置的是我们操作state对象属性的方法
 */
const mutations = {
    mutationsAddCount(state, n = 0) {
        return (state.count += n)
    },
    mutationsReduceCount(state, n = 0) {
        return (state.count -= n)
    }
}
export default new Vuex.Store({
    state,
    mutations
})
复制代码
然后我们在helloWorld.vue中,使用这个方法

还记得我们如何在组件中使用mutations吗?就和自定义事件非常相似

复制代码
<template>
  <div class="hello">
    <h3>{{$store.state.count}}</h3>
    <div>
      <button @click="handleAddClick(10)">增加</button>
      <button @click="handleReduceClick(10)">减少</button>
    </div>
  </div>
</template>
复制代码
复制代码
methods: {
    handleAddClick(n){
      this.$store.commit('mutationsAddCount',n);
    },
    handleReduceClick(n){
      this.$store.commit('mutationsReduceCount',n);
    }
  }
复制代码
来浏览器看一下效果如何!

我们可以看到每当触发事件时,我们都可以在vue开发工具中看到我们触发的mutations方法,以及参数

完美!



 

接下来就是actions,actions是异步操作

创建actions对象,并且使用

这里我在两个方法中使用了两个不同的参数,一个是context,它是一个和store对象具有相同对象属性的参数。在第二个函数中,我是直接使用了这个对象的commit的方法。

凭大家喜好就行

复制代码
const actions = {
    actionsAddCount(context, n = 0) {
        console.log(context)
        return context.commit('mutationsAddCount', n)
    },
    actionsReduceCount({ commit }, n = 0) {
        return commit('mutationsReduceCount', n)
    }
}
export default new Vuex.Store({
    state,
    mutations,
    actions
})
复制代码
在helloWorld.vue中

在methods中,增加两个方法,使用dispath来触发

 <div>异步操作</div>
  <div>
    <button @click="handleActionsAdd(10)">异步增加</button>
    <button @click="handleActionsReduce(10)">异步减少</button>
  </div>
复制代码
handleActionsAdd(n){
      this.$store.dispatch('actionsAddCount',n)
    },
    handleActionsReduce(n){
      this.$store.dispatch('actionsReduceCount',n)
    }
复制代码
进入浏览器看下效果如何!

最后就是getters

我们一般使用getters来获取我们的state,因为它算是state的一个计算属性

复制代码
const getters = {
    getterCount(state, n = 0) {
        return (state.count += n)
    }
}
export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters
})
复制代码
<h4>{{count}}</h4>
const getters = {
    getterCount(state) {
        return (state.count += 10)
    }
}
getters算是非常简单的了。

到这里,如果全都看懂了,vuex你已经没有压力了。

但是vuex官方给了我们一个更简单的方式来使用vuex, 也就是 {mapState, mapMutations, mapActions, mapGetters}

只要我们把上面基础的搞懂,这些都不在话下,只是方面我们书写罢了。

就这么简单,这里我们用到了es6的扩展运算符。如果不熟悉的同学还是去看看阮一峰大神的《Es6标准入门》这本书,我是看完了,受益匪浅!

复制代码
<script>
import {mapState, mapMutations, mapActions, mapGetters} from 'vuex'
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
    ...mapMutations({
      handleAddClick: 'mutationsAddCount',
      handleReduceClick: 'mutationsReduceCount'
    }),
    ...mapActions({
      handleActionsAdd: 'actionsAddCount',
      handleActionsReduce: 'actionsReduceCount'
    })
    // handleAddClick(n){
    //   this.$store.commit('mutationsAddCount',n);
    // },
    // handleReduceClick(n){
    //   this.$store.commit('mutationsReduceCount',n);
    // },
    // handleActionsAdd(n){
    //   this.$store.dispatch('actionsAddCount',n)
    // },
    // handleActionsReduce(n){
    //   this.$store.dispatch('actionsReduceCount',n)
    // }
  },
  computed: {
    count(){
      return this.$store.getters.getterCount
    }
  }
}
</script>
复制代码
 

同理,getters和 state也可以使用 mapState,mapGetters

 

如果你更懒的话,我们可以使用数组,而非对象,或者es6里面的对象简写方式

就像这种



 
原文地址:https://www.cnblogs.com/jinsuo/p/12145949.html