• vueX的使用


    vuex存储的信息在刷新完页面后,存储的数据会被清除;可以参考github项目:https://github.com/Little-Orange7/cmms-vue,在项目中的Vuex的使用,是存储用户的登录信息及菜单的路由信息;用户的登录信息也存到了sessionStorage中,当用户刷新页面时,菜单的路由信息就会被清除;

    一.模块结构

    一般大项目的vuex模块的结构如下:

    index.js:一般定义的是存储数据的状态(变量)。

    mutation-types.js:一般是定义mutations.js的方法名。

    mutations.js:一般是具体操作改变index.js中的变量的方法。

    actions.js:一般是调mutations.js中的方法,用法:this.$store.dispatch("mutations名", 参数);actions一般都是含有异步操作的时候使用。

    getters.js:一般是直接获取index.js中定义的变量的值方法。

    二.在index.js中要创建实例并导出

    import Vue from 'vue'
    import Vuex from 'vuex'
    import mutations from './mutations'
    import actions from './actions'
    import getters from './getters'
    
    Vue.use(Vuex)
    
    const state = {
      routes: [],
      keepAliveComps: [],
      user: JSON.parse(window.sessionStorage.getItem('user'))
    }
    
    const store = new Vuex.Store({
      state,
      mutations,
      actions,
      getters
    })
    
    export default store

    mutation.js主要操作state中的数据:

    import {
      INIT_ROUTES,
      INIT_USER,
      SET_KEEPALIVE
    } from './mutation-types.js'

    mutations.js中定义的方法:

    export default {
      [INIT_ROUTES] (state, data) {
        state.routes = data
      },
      [INIT_USER] (state, user) {
        state.user = user
      },
      [SET_KEEPALIVE] (state, compNames) {
        state.keepAliveComps = compNames
      }
    }

    在mutation-types.js中定义mutation方法名;

    export const INIT_USER = 'INIT_USER'
    export const INIT_ROUTES = 'INIT_ROUTES'
    export const SET_KEEPALIVE = 'SET_KEEPALIVE'

    三.在main.js中引入

    import store from './store'
    new Vue({
      router,
      store,
      render: h => h(App)
    }).$mount('#app')

    四.使用

    直接调mutations.js中的方法:

    this.$store.commit('SET_KEEPALIVE', this.mediList)

    如果使用actions,则调mutations方法:

    this.$store.dispatch("mutation方法名", 参数);

    commit和dispatch两者的区别:

    dispatch:含有异步操作,例如向后台提交数据,写法: this.$store.dispatch('mutations方法名',值),不能直接修改state,只能通过dispatch触发mutation来对state进行修改;
    commit:同步操作,写法:this.$store.commit('mutations方法名',值),直接修改state,并且是修改state的唯一途径;
  • 相关阅读:
    [Swift]LeetCode1109. 航班预订统计 | Corporate Flight Bookings
    [Swift]LeetCode1110. 删点成林 | Delete Nodes And Return Forest
    [Swift]LeetCode1111. 有效括号的嵌套深度 | Maximum Nesting Depth of Two Valid Parentheses Strings
    Live 2D所有模型展示图
    [Swift]LeetCode1108. IP 地址无效化 | Defanging an IP Address
    [CocoaPods]CocoaPods无法使用:Shell终端切换bash和zsh
    [Swift]完全透明沉浸式导航栏
    转 open_cursors参数设置调优
    模拟IO 读写压力测试
    转 DG switchover
  • 原文地址:https://www.cnblogs.com/littleorange7/p/12873097.html
Copyright © 2020-2023  润新知