vue2中使用vuex方法

136 阅读2分钟

前言:vuex是专门在Vue中实现集中状态(数据)管理的一个Vue插件,对Vue中应用中多个组件的共享状态进行集中式的管理(读/写),是一种组件间通信的方式,适合用于任意组件间通信。

vuex状态管理图

image.png

接下来,我们来一起了解怎么在Vue中去使用vuex吧

何时使用Vuex 多个视图依赖于同一状态。 来自不同视图的行为需要变更同一状态。 搭建vuex环境 Vuex插件的安装 注意:在vue2中,要用vuex的3版本;在vue3中,要用vuex的4版本; 以下用的是vue2,所以我们将下载vuex的3版本。

image.png

  1. 在src目录下创建名为store文件夹,再在tore文件夹中新建名为index.js文件。在该文件中引入vuex,创建store,以及导出store。
import Vue from 'vue'
//引入Vux
import Vuex from 'vuex';
//使用Vuex插件
Vue.use(Vuex)

//准备actions:用于响应组件中的动作
const actions = {}
//准备mutations:用于操作数据
const mutations = {}
//准备state:用于存储数据
const state = {}

//创建store
const store =new Vuex.Store({
    actions,
    mutations,
    state
})

//导出store
export default store

然后在main.js文件中进行挂载

import Vue from 'vue'
import App from './App.vue'

//引入store
import store from './store/index';

Vue.config.productionTip = false

new Vue({
  el:'#app',
  render: h => h(App),
  store,
  beforeCreate(){
    Vue.prototype.$bus=this
  }
})

Vuex基本使用

vuex小案例

  1. 当我们已经做好了以上的Vuex环境搭建工作后,在components文件夹下新建一个.vue文件,名叫TestCount.vue,并在App.vue文件中引入这个新建的.vue文件。

TestCount.vue文件代码如下:

<template>
        <div>
                <h2>当前值为:{{ $store.state.sum }}</h2>
                <button @click="increment">+3</button>
                <button @click="decrement">-3</button>
        </div>
</template>
<script>
export default {
        name: 'TestCount',
        data() {
                return {
                        n:3
                }
        },
        methods: {
                increment() {
                        this.$store.dispatch('jia',this.n);
                },
                decrement() {
                        this.$store.dispatch('jian',this.n);
                }
        },
}
</script>
  1. 在store文件夹下的index.js文件中的state初始化数据。
//准备state:用于存储数据
const state = {
    //初始化数据
    sum:0
}
  1. 在store文件夹下的index.js文件中的 actions、mutations中分别加入两个方法。
//准备actions:用于响应组件中的动作
const actions = {
    //响应组件加的动作
    jia(context,value){
        context.commit('JIA',value);
    },
    //响应组件减的动作
    jian(context,value){
        context.commit('JIAN',value);
    }
}
//准备mutations:用于操作数据
const mutations = {
    //执行加
    JIA(state,value){
        state.sum+=value;
    },
     //执行减
    JIAN(state,value){
        state.sum-=value;
    }
}

组件中读取vuex中的数据: $store.state.sum

组件中修改vuex中的数据: this.$store.dispatch(‘action中的方法名’,数据);或 context.commit(‘mutations中的方法名’,数据);

**注意:**若没有网络请求或其他业务逻辑,组件中也可以直接越过actions,也就是不写dispatch,直接写commit。

getters配置项

getters的作用是来将state中的数据进行加工。 此时,我们在上面的小案例中添加一个新的业务逻辑:将得到的sum值扩大5倍。我们在index.js文件中追加getters配置项。

........
const getters = {
    bigSum(){
        return state.sum*5
    }
}

//创建store
const store =new Vuex.Store({
    ..........
    getters
})

组件中读取数据: $store.getters.bigSum

四个map方法的使用

mapState方法:用于帮助我们映射state中的数据为计算属性

import { mapState } from 'vuex'
//.........
computed: {
...mapState([
  // 映射 this.count 为 store.state.count
  'count'
])
}

mapGetters方法: 用于帮助我们映射Getters中的数据为计算属性


import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}

mapActions方法用于帮助我们生成与Actions对话的方法,即包含 this.$store.dispatch(xxx)的函数。

import { mapActions } from 'vuex'
//.........
methods: {
  ...mapActions([
    'add', 
    'reduce' 
  ])
}

mapMutations方法: 用于帮助我们生成与Actions对话的方法,即包含 this.$store.commit(xxx)的函数。

import { mapMutations } from 'vuex'
//.........
methods: {
  ...mapMutations([
    'Jia', 
    'jian' 
  ])
}

备注: mapActions和mapMutations方法使用时,若需要传参:在模板中绑定事件时传递好参数,否则参数是事件对象.