Vuex在开发中的使用详解

Vuex在开发中的使用详解

核心概念

State
Getter
Mutation
Action
Module


State

定义共享的状态变量,相当于store中的data
通过mapState方法映射到computed中

Getter

读取器,相当于store中的computed属性
通过mapGetter方法映射到computed中

Mutation

修改器,用于修改state中的变量状态

Action

向store发出调用通知,用于提交mutation,相当于store中的methods
通过mapActions方法映射到methods中
action函数接收一个与store实例具有相同方法和属性的context对象,因此可以使用context.commit提交一个mutations

Module

将 store 分割成模块(module)

开发实例

  • 项目结构

这里写图片描述

1.state.js

export default {
  companyInfo: [
    {
      id: 1,
      name: '选项1',
      status: true
    },
    {
      id: 2,
      name: '选项2',
      status: false
    },
    {
      id: 3,
      name: '选项3',
      status: true
    },
    {
      id: 4,
      name: '选项4',
      status: true
    },
    {
      id: 5,
      name: '选项5',
      status: false
    },
    {
      id: 6,
      name: '选项6',
      status: true
    }
  ],
  helloWord: 'Hello Word!'
};

2.getters.js

export default {
  values: state => Object.values(state.companyInfo)
};

3.mutation-types.js

// 使用常量替代 Mutation 事件类型
// 名字可以自己定,建议使用与action方法名一致的名字,这样在多人开发的方便查看
export const CHANGE_DATA = 'change_data';

4.mutations.js

// 按 es6 的规范 import * as obj from "xxx" 会将 "xxx" 中所有 export 导出的内容组合成一个对象返回
import * as types from './mutation-types';
export default {
  getCompanyInfoId (state, data) {
    state.companyInfo.router = 'www.baidu.com' + data;
  },
  [types.CHANGE_DATA] (state, data) {
    state.helloWord = data;
  }
};

5.actions.js

import * as types from './mutation-types.js';
export default {
  //  此处使用了ES6函数参数的解构,在需要多次提交mutations时
  // 不用使用context.commit来提交,而是直接使用commit提交
  getMutation ({ commit }) {
    commit({
      type: 'getCompanyInfoId',
      amount: 10
    });
  },
  changeData ({ commit }) {
    commit(types.CHANGE_DATA, 'data change success');
  }
};

6.index.js 将state.js、getters.js、mutations.js、actions.js文件进行整合,作为store的出口

import Vue from 'vue';
import Vuex from 'vuex';
import List from './List';
Vue.use(Vuex);
let Store = new Vuex.Store({
  modules: {
    List
  }
});
export default Store;

7.home.vue

<template>

</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex';
export default {
  data () {
    return {
    };
  },
  computed: {
    ...mapState({
      List: state => state.List.companyInfo,
      helloWord: state => state.List.helloWord
    }),
    ...mapGetters(['values'])
  },
  methods: {
    ...mapActions(['changeData']),
  },
  created () {

    this.changeData();
};
</script>
<style scoped lang="scss">

</style>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值