vue+store 的模块导入学习

由于项目用不到太多store中的数据转换,故以前都是直接写的store代码没有引用,调用可谈,用在简单项目上也着是方便。
近期分析了vue-elementui-admin代码后,学习到了好的store代码的使用方式,故此记录

首先从目录上

modules中存放store逻辑代码
在这里插入图片描述
getters.js中获取到modules中的各种数据

const getters = {
  sidebar: state => state.app.sidebar,// app为js文件名,sidebar为app中的state中的属性
  device: state => state.app.device,
  token: state => state.user.token,
  avatar: state => state.user.avatar,
  name: state => state.user.name,
  roles: state => state.user.roles,
  logo: state => state.user.logo,
  visitedViews: state => state.tagsView.visitedViews,
  cachedViews: state => state.tagsView.cachedViews
}
export default getters

index.js中使用moudules与getters.js中数据

import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'

Vue.use(Vuex)

const modulesFiles = require.context('./modules', true, /\.js$/)

// 您不需要从“./modules/app”导入应用程序。
// 它将自动要求模块文件中的所有Vuex模块
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

此时store
在这里插入图片描述
用法

import store from './store'

this.$store.dispatch('tagsView/addVisitedView', tag) // 调用方法

this.$store.state.app.device // 获取数据
this.$store.getters.logo
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值