vuex学习心得

Vuex

通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store访问到

每一个 Vuex 应用的核心就是 store(仓库)。"store" 基本上就是一个容器,它包含着你的应用中大部分的状态(state)Vuex 和单纯的全局对象有以下两点不同:

1、Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。

2、你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交(commit) mutations。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。

const store = new Vuex.Store({ state: { count: 0 },

     mutations: { increment (state) { state.count++ } }

 })

Vuex分模块

例子,控制用户信息弹窗变量存入vuex里面

用到的变量都需提前申明

const state = {
projectInfo: null,
userInfo: null,
urlLink: [], // 路由列表
routerList: [],
realName: '',
loginImageUrl: '',
userInfoDialog: false,
};

 

先申明弹窗关闭和开启的两个变量,可使用常量替代mutation事件类型。

user.js里面引入

import * as mutationTypes from '../mutation-types';

const mutations ={
    [mutationTypes.CTR_USERINFO_DIALOG_OPEN](state) {
        state.userInfoDialog = true;
    },
    [mutationTypes.CTR_USERINFO_DIALOG_CLOSE](state) {
        state.userInfoDialog = false;
    },
}

在触发弹窗关闭的js里添加

methods: {
    resetDialogFlag() {
        this.$store.commit('CTR_USERINFO_DIALOG_CLOSE');
    },
}

监测this.$store.state.user.userInfoDialogdialogFlag来代替

computed: {

    dialogFlag() {

        return this.$store.state.user.userInfoDialog;

    },

},

页面dom

<el-dialog class="info-setting"

@close="resetDialogFlag"

v-model="dialogFlag">

以上只是单纯的交互没有调动接口。若要用到接口需使用action

例子:获得左侧菜单栏

action-type.js里面加

export const GET_ROUTER_LIST = 'GET_ROUTER_LIST';

user.js里面加

import * as actionTypes from '../action-types';
const mutations = {

    [actionTypes.GET_ROUTER_LIST]({ commit }) {

        api.account_showMenuList({ accountId: util.getCookie('accountId') })

        .then((res) => {

            if (res && res.data) {

                commit('SAVE_ROUTER_LIST', res.data);

            }

        });

    },
} 

当用户角色变化或者账号变化时调用

this.$store.dispatch('GET_ROUTER_LIST');

如上代码调用接口把数据请求回来,再调用mutation来存数据

mutation对象里添加这个

[mutationTypes.SAVE_ROUTER_LIST](state, data) {

    state.routerList = data;

},

在左侧菜单栏组件里

computed: {

    recommendTpl() {

        return this.$store.state.user.routerList;
    
    },

}, 
<div :default-active="curindex"

class="router-aside">

<template v-for="item in recommendTpl">

<router-link class="menu-item" :class="item.menuTitle"

:to="item.menuUrl">{{item.menuDesc}}</router-link>

</template>

</div>
原文地址:https://www.cnblogs.com/nanacln/p/7099487.html