zoukankan      html  css  js  c++  java
  • VUEX 状态管理

    VUEX 是VUE提供的一个状态管理工具,具体他能做什么呢,比如有这样的业务场景:

    用户在登录后,可以设置他的登录信息。去到用户主页,就可以显示这个用户的登录信息。

    其实就是用来在不同的组件之间共享信息。

    我们使用 vue-element-admin 为例,来讲解VUEX的使用。

    import Vue from 'vue'
    import Vuex from 'vuex'
    import getters from './getters'
    import app from './modules/app'
    import settings from './modules/settings'
    import user from './modules/user'
    
    Vue.use(Vuex)
    
    
    const store = new Vuex.Store({
      modules: {
        app,
        settings,
        user
      },
      getters
    })
    
    export default store

    构建store,这个store 支持模块,在这个store中有三个模块。

    app 模块定义

    import Cookies from 'js-cookie'
    
    const state = {
      sidebar: {
        opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
        withoutAnimation: false
      },
      device: 'desktop'
    }
    
    const mutations = {
      TOGGLE_SIDEBAR: state => {
        state.sidebar.opened = !state.sidebar.opened
        state.sidebar.withoutAnimation = false
        if (state.sidebar.opened) {
          Cookies.set('sidebarStatus', 1)
        } else {
          Cookies.set('sidebarStatus', 0)
        }
      },
      CLOSE_SIDEBAR: (state, withoutAnimation) => {
        Cookies.set('sidebarStatus', 0)
        state.sidebar.opened = false
        state.sidebar.withoutAnimation = withoutAnimation
      },
      TOGGLE_DEVICE: (state, device) => {
        state.device = device
      }
    }
    
    const actions = {
      toggleSideBar({ commit }) {
        commit('TOGGLE_SIDEBAR')
      },
      closeSideBar({ commit }, { withoutAnimation }) {
        commit('CLOSE_SIDEBAR', withoutAnimation)
      },
      toggleDevice({ commit }, device) {
        commit('TOGGLE_DEVICE', device)
      }
    }
    
    export default {
      namespaced: true,
      state,
      mutations,
      actions
    }

    actions: 就是提供给外部调用。

    state: 就是app定义的状态

    namespaced:支持命名空间

    toggleSideBar() {
          this.$store.dispatch('app/toggleSideBar')
        }

    这里我们可以看到可以通过 this.$store.dispatch 触发action方法。

  • 相关阅读:
    几款比较好用的思维导图工具
    单例模式的七种实现
    从中央仓库下载所想要的jar包
    单例模式实现的几种方式
    两个数组比较看看结果
    CSS 基础 例子 伪元素和伪类 & 区别
    CSS 基础 例子 背景色 & 背景图片
    CSS 基础 例子 水平 & 垂直对齐
    CSS 基础 例子 浮动float
    CSS 基础 例子 行高line-height
  • 原文地址:https://www.cnblogs.com/yg_zhang/p/10858166.html
Copyright © 2011-2022 走看看