关于vuex 的模块开发和使用

1、文件结构

2、modules 文件内容

例子: ccc.js 文件内容如下:

bash 复制代码
// 基础配置项
const state = {
  aa: []
}

const mutations = {
  setaa (state, data) {
    state.aa= data
  }
}

const actions = {}
export default {
  namespaced: true, 
  state,
  mutations,
  actions
}
**注意:::**
// namespaced为true的作用是告诉vuex,该模块所有的state 、mutations、actions里面的东西调用时都需要加上命名空间,这个命名空间就是该模块被improt时命名的名字。

3、getters.js 文件

bash 复制代码
const getters = {
  control: (state) => state.ccc.aa,
  // 此处为了 集合 gettees 数据 通过辅助函数使用: 注意写法 state.文件名字.参数名字(即哪个文件下的那个参数)
}
export default getters

4、index.js 文件:把state 和 getters 挂载到vuex 上

bash 复制代码
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'

Vue.use(Vuex)

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

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

注意使用: 在vue文件中 引入 辅助函数

1、引入 import { mapGetters } from 'vuex'

2、在计算属性 computed 使用 辅助函数即可,

bash 复制代码
computed: {
    ...mapGetters(['control']), // 为getters 中的 字段名:::
}

参考:https://vuex.vuejs.org/zh/

vuex : 数据

1、state: 它便作为一个"唯一数据源 (SSOT)"而存在

2、getter: "getter"(可以认为是 store 的计算属性),第一个参数是 state,

mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:

3、Mutation:更改 Vuex 的 store 中的状态的唯一方法是提交 mutation

并且它会接受 state 作为第一个参数

类似:methods:{ }

通过store.commit('方法名字',参数二)进行更改 store 中的数据

4、Action: Action 类似于 mutation , 可以包含任意异步操作

Action 通过 store.dispatch 方法触发

store.dispatch('increment')

使用 mapActions 辅助函数

5、Module :Vuex 允许我们将 store 分割成模块(module)

相关推荐
神之王楠8 分钟前
如何通过js加载css和html
javascript·css·html
余生H13 分钟前
前端的全栈混合之路Meteor篇:关于前后端分离及与各框架的对比
前端·javascript·node.js·全栈
花花鱼14 分钟前
@antv/x6 导出图片下载,或者导出图片为base64由后端去处理。
vue.js
程序员-珍16 分钟前
使用openapi生成前端请求文件报错 ‘Token “Integer“ does not exist.‘
java·前端·spring boot·后端·restful·个人开发
axihaihai20 分钟前
网站开发的发展(后端路由/前后端分离/前端路由)
前端
流烟默32 分钟前
Vue中watch监听属性的一些应用总结
前端·javascript·vue.js·watch
2401_8572979143 分钟前
招联金融2025校招内推
java·前端·算法·金融·求职招聘
茶卡盐佑星_1 小时前
meta标签作用/SEO优化
前端·javascript·html
与衫1 小时前
掌握嵌套子查询:复杂 SQL 中 * 列的准确表列关系
android·javascript·sql
Ink1 小时前
从底层看 path.resolve 实现
前端·node.js