zoukankan      html  css  js  c++  java
  • 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的唯一途径;
  • 相关阅读:
    <c:forEach 的常用整理
    <div>
    HTML <td> 标签的 rowspan 属性
    ap-client.xml要配
    @Autowired
    hasResultError
    使用 EclEmma 进行覆盖测试
    IE调试网页之三:使用 F12 工具控制台查看错误和状态 (Windows)
    different between<A Href> and <jsp: forward>
    <button>与<input type="button">的区别
  • 原文地址:https://www.cnblogs.com/littleorange7/p/12873097.html
Copyright © 2011-2022 走看看