关于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)

相关推荐
万少20 分钟前
给 DeepSeek Harness 装个"应用商店":一条命令,595 个插件随你逛
前端·javascript·后端
波波00736 分钟前
C# 15 重磅新特性: 带标签 break 与 continue:重新定义嵌套循环控制流
服务器·前端·c#
Brown.alexis1 小时前
es6知识点1-自备使用
前端·ecmascript·es6
小爬的老粉丝2 小时前
JavaScript 纯前端预览 WPS:先识别容器,再路由解析器
前端·javascript·wps
计算机魔术师3 小时前
新兴多智能体系统的模式与问题
前端
用户059540174463 小时前
AI Agent 上下文污染踩坑实录:用 pytest + Redis 揪出 3 类记忆串号 bug,排查 6 小时
前端·css
满栀5854 小时前
状态管理:Redux、Vuex、Pinia 核心区别
前端·javascript·typescript
一拳不是超人4 小时前
DeepSeek Harness 为什么敢说"一切皆插件"?拆透 Cordis 引擎的五大核心机制
前端·人工智能·agent
IT_陈寒4 小时前
Python的GIL让我多写了500行代码
前端·人工智能·后端
风骏时光牛马4 小时前
AI智能体能力调度微服务
前端