mutation结合action的使用(vuex2.0)

来源:互联网 发布:python tolist 编辑:程序博客网 时间:2024/06/05 19:10

1, mutation
The only way to actually change state in a Vuex store is by committing a mutation, 在vue 中,只有mutation 才能改变state. mutation 类似事件,每一个mutation都有一个类型和一个处理函数,因为只有mutation 才能改变state, 所以处理函数自动会获得一个默认参数 state. 所谓的类型其实就是名字,action去comit 一个mutation, 它要指定去commit哪个mutation, 所以mutation至少需要一个名字,commit mutation 之后, 要做什么事情,那就需要给它指定一个处理函数, 类型(名字) + 处理函数就构成了mutation. 现在store.js添加mutation.
代码结构如下所示:
  这里写图片描述
2、actions.js

//引入后端接口import {getPhoneType} from '../api/common/common';//从后端获取手机类型(集合)export const fetchPhoneType = ({commit}) => {    getPhoneType().then((res)=>{          commit('FETCHPHONETYPE', res.data.records);    });}//缓存存储数据//组织IDexport const setOrgId = ({commit}, data) => {    commit('SETORGID', data)}

3、getters.js

//获取手机类型export const getPhoneType= state => {    return state.phoneType;};//获取组织IDexport const getOrgId =state =>{    return state.orgId;}

4、store.js

import Vue from 'vue'import Vuex from 'vuex'import * as actions from './actions'import * as getters from './getters'Vue.use(Vuex)// default stateconst state = {    phoneType:[],    orgId:''}//  mutations//Vue 建议我们mutation 类型用大写常量表示,修改一下,把mutation 类型改为大写const mutations = {    FETCHPHONETYPE(state, data) {        state.phoneType = data;    },    SETORGID(state, data) {        state.orgId = data;    }}// storeexport default new Vuex.Store({    actions,    getters,    state,    mutations});

5、xxx.vue中使用

<template>   <div>       .....   </div> </template><script>     //引入vuex    import { mapGetters, mapActions } from 'vuex';    export default{        data(){           return{           }        },        computed: {            phoneType: function(){                return this.getPhoneType();            },            orgId: function(){                return this.getOrgId();            }        },        methods:{              ...mapActions([                'fetchPhoneType','setOrgId'            ]),            ...mapGetters([                'getPhoneType','getOrgId'            ])         },        mounted(){            this.fetchPhoneType();//获取手机类型的数据            this.setOrgId('2333');//设置组织ID        }           } </script><style></style>