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

相关推荐
宿6749 小时前
vue3-包管理器
前端·vue.js
@PHARAOH9 小时前
WHAT - Remix 入门和基本实践:理解两套产物
前端·remix
mayaairi10 小时前
Vue2 生命周期完全指南:从创建到销毁的8个钩子函数
前端·javascript·vue.js
研☆香11 小时前
一个简单的气泡弹窗制作
javascript
xy345311 小时前
axure9.0 如何打造一个计时器(简单版)
前端·ui·html·axure·原型·产品设计
大模型丫丫11 小时前
用 TypeScript、NestJS 和 LangGraph 搭建一个可控的 AI Agent
javascript·人工智能·typescript
IMPYLH11 小时前
HTML 的 <pre> 元素
前端·javascript·html
shmily麻瓜小菜鸡12 小时前
JavaScript / TypeScript 易踩坑知识点 —— 异步编程类
开发语言·javascript·typescript
tsumikistep12 小时前
【前端】Vue + Axios 跨域问题实战:7070 代理转发 8080 + 401 报错分析(黑马外卖)
前端·javascript·vue.js
lichenyang45312 小时前
鸿蒙首页从等高商品 Grid 到双列瀑布流:同一张图也能做出小红书式浏览节奏
前端