位置:- 正文

【vue】vuex中modules的基本用法(vuex model)

编辑:rootadmin
【vue】vuex中modules的基本用法

推荐整理分享【vue】vuex中modules的基本用法(vuex model),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:vue modal,vuex moudle,vue module,vuex model,vuex moudle,vuex中的module,vuex moudles,vuex moudles,内容如对您有帮助,希望把文章链接给更多的朋友!

1,什么时候用modules

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。 为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割 在模块中使用:namespaced: true, 命名空间,添加之后,当前模块下的标识符可以和其它模块相同,用于解决不同模块的命名冲突问题

2,store文件结构

3.1 index.js中手动引入modules

import Vue from 'vue'import Vuex from 'vuex'import bus from './modules/bus'import app from './modules/app'const path = require('path')Vue.use(Vuex)let store = new Vuex.Store({ state: { }, mutations: { }, actions: { }, modules: { namespaced: true, app, bus }});export default store

3.2 index.js 中动态引入modules

import Vue from 'vue'import Vuex from 'vuex'const path = require('path')Vue.use(Vuex)const files = require.context('./modules', false, /\.js$/)let modules = {}files.keys().forEach(key => { let name = path.basename(key, '.js') modules[name] = files(key).default || files(key)})let store = new Vuex.Store({ state: { }, mutations: { }, actions: { }, modules});export default store

4,app.js 文件中代码

let user = { namespaced: true, state: {}, mutations: { setUser(state, val) { state.user = val; } }, getters: {}, actions: { setName(state, val) { return new Promise(resolve => { setTimeout(function () { state.user = val; resolve(state.user); }, 2000) }) } }}export default user;

 5,配置main.js,挂载store

new Vue({ el: '#app', router, store, components: { App: App }, template: '<App/>'})【vue】vuex中modules的基本用法(vuex model)

6,vue中使用

// commit 执行mutations里的方法,同步操作 this.$store.commit('app/setUser', {name: '张三'}); console.log(this.user.name); // dispatch 执行actions里的方法,异步操作 this.$store.dispatch('app/setName', {name: '李四'}).then(res => { console.log(res.name); })

7,js中使用

// 引入 这里的store 就相当于页面中的 this.$storeimport store from '@/store'export const setCurUser = (user) => { let curUser = store.app.user if(!curUser) { store.commit("app/setUser", user) return user } return curUser}

注意:

1,vue和vuex的版本搭配

vue2使用vuex3;vue3使用vuex4. 否则会出现this.$store为undefined错误

延伸:

1,vuex的五种状态 state、getter、mutation、action、module

state:所有共享数据统一放到state中,与data类似

mutation: 类似于事件,用于改变状态

action: 和mutation相似,但是action是异步操作

getter: 类似vue中的computed,进行缓存,形成新的数据

modules: 分模块,大型项目一个对象管理会很臃肿

本文链接地址:https://www.jiuchutong.com/zhishi/292954.html 转载请保留说明!
下一篇链接:https://www.jiuchutong.com/zhishi/292955.html
免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

鄂ICP备2023003026号

友情链接: 武汉网站建设 电脑维修 湖南楚通运网络