首页 > 其他 > 详细

vueX的使用

时间:2020-05-12 01:06:33      阅读:59      评论:0      收藏:0      [点我收藏+]

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的唯一途径;

 

vueX的使用

原文:https://www.cnblogs.com/littleorange7/p/12873097.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!