vue store用法
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
首字母不能大写
export default new Vuex.Store({
state: {
//这里放全局参数
调用 this.$store.state.online
模块调用this.$store.state.a.online
test1:‘1111’,
test2:‘2222’,
userId: userJs.getUserId() || "", // 用户id
username: userJs.getUsername() || "", // 登录名
name: userJs.getName() || "" // 姓名
},
getters: {
//这里是get方法,并且每次打开浏览器优先执行该方法,获取所有的状态
//不能传递参数 ,只能对state数值进行计算不能修改
调用this.$store.getters.getTest
this.$store.getters.计算属性名 // 不分模块
this.$store.getters['模块名/计算属性名'] // 分模块
import { mapGetters } from
'vuex'
computed: {
// 不分模块
...mapGetters([
'计算属性名'
])
// 分模块,不重命名计算属性
...mapGetters(
'模块名'
, [
'计算属性名'
])
// 分模块,重命名计算属性
...mapGetters(
'模块名'
, {
'新计算属性名'
:
'旧计算属性名'
})
}
this。计算属性名 使用
getTest(state) {
// return state.test1 + state.test2;
},
//getTest: state =>state.test1 + state.test2,
多模块多个state 找全局变量还需要分模块找,也可以通过getters把所有模块的共有变量都集成在一起
/*
const getters = {
userInfo: state => state.user.userInfo,
sidebar: state => state.app.sidebar,
visitedViews: state => state.tagsView.visitedViews,
permission_routes: state => state.permission.routes,
dictionaryList: state => state.base.dictionaryList,
}
export default getters
*/
},
mutations: {
//mutations中的方法一般用常量(大写)不是常量大小写都行
//这里是set方法,mutation是修改state的唯一方法。函数中只能执行 同步函数
mutation调用方法
this.$store.commit(“mutation函数名”,发送到mutation中的数据)
模块调用this.$store.commit('modulesB/UPDATE_TO_VIP2')
m_set_ajax_loading (state, bl) {
state.ajax_loading = bl
}
},
actions: {
action的功能和mutation是类似的,都是去变更store里的state,不过action和mutation有两点不同:
1.action主要处理的是异步的操作,mutation必须同步执行,而action就不受这样的限制,也就是说action中我们既可以处理同步,也可以处理异步的操作
action函数中能执行异步函数, mutation函数中不可以
2.action改变状态,最后是通过提交mutation,就是action只能通过mutation中修改state的值。
action调用方法
this.$store.dispatch(‘action中的函数名’,发送到action中的数据)
模块调用this.$store.dispatch('modulesB/UPDATE_TO_VIP2')
}
})
store
普通加载模块
const store = new Vuex.Store({
modules: {
user: user,
tagsView: tagsView
},
state,
getters,
mutations,
actions
});
==============================================================================
自动加载模块
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
Vue.use(Vuex)
// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)
// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
// set './app.js' => 'app'
const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
const value = modulesFiles(modulePath)
modules[moduleName] = value.default
return modules
}, {})
const store = new Vuex.Store({
modules,
getters
})
export default store
posted on 2022-07-28 17:33 867511789 阅读(1642) 评论(0) 编辑 收藏 举报