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

    VUEX 状态管理

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

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

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

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

    //store/index.js
    
    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,
      plugins:[
         
    ] 
    })
    
    export default store

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

    app 模块定义

    //modules/app.js
    
    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方法。

  • 相关阅读:
    Cayley's Tree Formula & Prufer's Method
    POJ 2262:Goldbach's Conjecture
    The Sieve of Eratosthenes (素数筛选法)
    POJ 2244:Eeny Meeny Moo(稍加变形的约瑟夫问题)
    POJ 1595:Prime Cuts
    iframe标签的使用
    js笔记
    Asp.Net知识点
    Reapte控件的使用
    浮躁十年
  • 原文地址:https://www.cnblogs.com/tommymarc/p/12143408.html
Copyright © 2011-2022 走看看