vuex - Module - 访问命名空间里的state、actions、mutations、getters的方式

news/2024/7/10 1:52:53 标签: vue

vuex - Module - 访问命名空间里的state、actions、mutations、getters的方式

  • 1. vuex
    • 1.1. 作用
    • 1.2. 成员及作用
  • 2. 模块(module)说明
  • 3. 要点及注意点
    • 3.1. namespaced: true
    • 3.2. 辅助函数写在哪里?
  • 4. 演示代码概览
  • 5. state
    • 5.1. 全局变量获取和辅助函数获取
    • 5.2. 代码总结
    • 5.3. 实际开发的中主模块中使用getters-快捷访问
  • 6. actions
    • 6.1. 全局变量获取和辅助函数获取
    • 6.2. 代码总结及操作演示
  • 7. mutations
    • 7.1 全局变量和辅助函数获取
    • 7.2 代码总结
  • 8. getters
    • 8.1 全局变量获取和辅助函数获取
    • 8.2. 代码总结

vuex_1">1. vuex

1.1. 作用

  • 用来统一管理项目的状态(公用数据)

1.2. 成员及作用

  1. state: 存储状态
  2. getters: state的计算属性
  3. mutations: 修改状态(同步操作)
  4. actions:修改状态(异步操作)
  5. modules: 数据模块化



2. 模块(module)说明

注: 本小节内容来源官网
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

const moduleA = {
  namespaced: true,  //区分和其他模块及主模块中的内容,防止冲突
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  namespaced: true,  //区分和其他模块及主模块中的内容,防止冲突
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

虽然模块化的引入, 有利于vuex中对状态和函数的维护和开发, 但与之带来的还有获取上的困扰, 以下内容为获取各配置项中内容的讲解.



3. 要点及注意点

3.1. namespaced: true

  • 保证内部模块的高封闭性;
  • 默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的, 可以直接调用, 但是很容易和其他子模块及主模块中, 同名状态或者函数发生冲突, 在子模块的配置项目中, 必须添加 namespaced: true 属性, 区分和其他模块及主模块中的同名状态或者函数, 防止冲突;
  • 后面需要访问子模块中的内容就需要带模块名.

3.2. 辅助函数写在哪里?

  • 针对于各配置项, 共有四个辅助函数, 用于访问命名空间里的内容, mapState, mapMutations, mapActions, mapGetters,
    • mapState, mapGetters , 中存的是状态(数据), 因此在子组件的计算属性 computed 中使用;
    • mapMutations, mapActions中存的是函数, 因此在子组件的 methods 使用;



4. 演示代码概览

在这里插入图片描述

  • user子模块不做获取演示, 仅仅为了体现子模块



5. state

  • 获取order子模块中的 price:'998’

5.1. 全局变量获取和辅助函数获取

  1. 全局变量之 - 插值表达式获取
    • 格式: $store.state.模块名.模块属性
    • 实现代码: $store.state.order.price
  2. 全局变量之 - 计算属性获取
    • 和上一个相同, 仅仅写在计算属性中, 前面加一个this
    • 实现代码: this.$store.state.模块名.模块属性
  3. 辅助函数 - 数组形式
    • 格式: ...mapState('模块名', ['属性名'])
    • 实现代码: …mapState(‘order’, [‘price’])

5.2. 代码总结

<template>
  <div>
    <h1>modules</h1>
    <pre>
      <!-- 获取order中的价格 "998" -->
      1.1 全局变量之 - 插值表达式获取   
      {{ $store.state.order.price }}

      1.2 全局变量之 - 计算属性获取   
      {{ myPrice }}

      1.3. 辅助函数之-数组形式        
      {{ price }}               

    </pre>
  </div>
</template>
<script>
import { mapState } from 'vuex'
export default {
  name: 'modules',

  computed: {
    myPrice(){
      return this.$store.state.order.price 
    },
    ...mapState('order', ['price'])
  }
  
}
</script>

5.3. 实际开发的中主模块中使用getters-快捷访问

实际开发中, 以上方式较少用, 一般来说子模块中state里的数据, 都会在主模块中的getters写好, 方便获取
在这里插入图片描述


6. actions

6.1. 全局变量获取和辅助函数获取

  1. 全局变量获取

    1. 格式: this.$store.dispatch('模块名/actions中的方法名', '实参')
    2. this.$store.dispatch(‘order/editTxt’, ‘跳楼大甩卖’)
  2. 赋值函数 - 数组形式

    1. 格式:

      methods:{
      	// 获取方法
      	...mapActions(['模块名/actions中的方法名'])
      	
      	//  调用
      	this['模块名/actions中的方法名'](实参)
      }
      
    2. 代码实现

      methods:{
      	...mapActions(['order/editTxt']),
      
       	this['order/editTxt']('优惠大酬宾')
      }
      
  3. 赋值函数 - 对象形式

    1. 格式:

      methods:{
      	...mapActions({
      		 aaa: '模块名/actions中的方法名'
      	 }),
      	
      	//  调用
      	this.aaa(实参)
      }
      
    2. 代码实现

      methods:{
      	...mapActions({
      		aaa: 'order/editTxt'
      	}),
      	
       	this.aaa('大大促销')
      }
      



6.2. 代码总结及操作演示

  • vuex子模块中定义:
const state = {
    price:'998',
    num:9999,
    desc:{
        txt:'便宜实惠!'
    }
}
const actions = {
    editTxt(context, payload){
        context.commit("editTxt", payload)
    },
}
const mutations = {
    editTxt(state, payload){
        state.desc.txt = payload
    }
}
const getters = {}

export default {
    namespaced: true,
    state,
    actions,
    mutations,
    getters
}
  • 组件中使用:
<template>
  <div>
    <h1>modules</h1>
    <pre>
      3.actions                        <br>
     desc: {{ $store.state.order.desc.txt }}

      <button @click=clk1>
        把desc'便宜实惠!'改成'大大促销'
      </button>

      <button @click=clk2>
        把desc'便宜实惠!'改成'跳楼大甩卖'
      </button> 
        
      <button @click=clk3>
        把desc'便宜实惠!'改成'优惠大酬宾'
      </button>  </pre>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  methods: {
    ...mapActions({
      aaa: 'order/editTxt'
    }),
    clk1 () {
      this.aaa('大大促销')
    },
    clk2 () {
      this.$store.dispatch('order/editTxt', '跳楼大甩卖')
    },
    ...mapActions(['order/editTxt']),
    clk3 () {
      this['order/editTxt']('优惠大酬宾')
    }
  }
}
</script>

操作演示:
ddd


7. mutations

7.1 全局变量和辅助函数获取

  1. 全局变量获取

    1. 格式: this.$store.commit('模块名/actions中的方法名', '实参')
    2. this.$store.commit(‘order/editTxt’, ‘跳楼大甩卖’)
  2. 辅助函数获取
    mutations的辅助函数是mapMutations, 辅助函数的使用方式和actions一致, 不做赘述

7.2 代码总结

  • vuex子模块中定义:
const state = {
    price:'998',
    num:9999,
    desc:{
        txt:'便宜实惠!'
    }
}
const actions = {}

const mutations = {
    editNum(state, payload){
        state.num = payload
    }
}
const getters = {}

export default {
    namespaced: true,
    state,
    actions,
    mutations,
    getters
}
  • 组件中使用:
<template>
  <div>
    <h1>modules</h1>
    <pre>
      mutations
        num9999 --> {{$store.state.order.num}}

        1.全局变量
        <button @click=clk1>把num'9999'改成'1111'</button>
        2.辅助函数-对象
        <button @click=clk2>把num'9999'改成'2222'</button>
        2.辅助函数-数组
        <button @click="clk3 ">'9999'改成'3333'</button>
      </pre>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
export default {
  methods: {
    ...mapMutations({
      ccc: 'order/editNum',
    }),
    ...mapMutations(['order/editNum']),
    clk1(){
      this.$store.commit('order/editNum',1111)
    },
    clk2(){
      this.ccc(2222)
    },
    clk3(){
      this['order/editNum'](3333)
    }
  }
}
</script>



8. getters

注意:

  1. vuex中的getter , 可以认为是 store 的计算属性 。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
  2. 实际开发中, 并不会使用子模块的getters, 因为它的存在本来就是给开发者提供快捷访问, 简化编码, 只有写在主模块中才能满足设计getters的出发点。

8.1 全局变量获取和辅助函数获取

  1. 全局变量获取
    1. 格式: $store.getters['模块名/getters中的属性名']
    2. 代码实现: $store.getters[‘order/customTxt’]

  2. 辅助函数获取
    1. 格式:

    computed: {
    	...mapGetters({
    		myTxt: '模块名/getters中的属性名
    	}),
    }
    

8.2. 代码总结

  • vuex子模块中定义
const state = {
    price:'998',
    num:9999,
    desc:{
        txt:'便宜实惠!'
    }
}
const actions = {}

const mutations = {}
const getters = {
    customTxt(state){
        return state.desc.txt
    }
}

export default {
    namespaced: true,
    state,
    actions,
    mutations,
    getters
}
  • 组件中使用
<template>
  <div>
    <h1>modules</h1>
    <pre>
        desc:便宜实惠! --> {{$store.state.order.desc.txt}}
        
        getters
        方式一:全局变量  {{ $store.getters['order/customTxt'] }}
        方式一:辅助函数  {{ myTxt }}
      </pre>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  computed: {
    ...mapGetters({
      myTxt: 'order/customTxt'
    }),
  }
}
</script>

http://www.niftyadmin.cn/n/1263670.html

相关文章

npm-查看包所有版本和下载指定版本包

以jquery为例: 查看包所有版本 npm view jquery versions下载指定版本包 npm install jquery1.12.4

关于!!+Cookies.get(‘sidebarStatus‘)讲解

文章目录问题引入作用及文件位置作用文件位置!!Cookies.get(sidebarStatus)详细详解总结问题引入 在vue-element-admin框架中, vuex的app子模块中有这段代码: opened: Cookies.get(sidebarStatus) ? !!Cookies.get(sidebarStatus) : true,其中的 !!Cookies.get(sidebarStatu…

父子传值, 报错

单向数据流, 子组件不允许修改父组件的数据, 否则报错

vue 分页删除最后一条数据,返回上一级的分页

需求: 在删除某一页的唯一条数据时, 能成功跳转回删除操作页的上一页 async del (id) {try {await this.$confirm(确定删除吗?, 警告)/*** vue 分页删除最后一条数据&#xff0c;返回上一级的分页* * 这两个数据都是在 "data" 中定义的* this.totaData: 总数据数量*…

UE4 TCP通信 (UE作为客户端接收字节)

在上一篇(UE4 TCP通信)基础上,实现UE客户端接收服务端推送的字节数据并解析。 效果 (注意看左上角的打印信息) 步骤 1. 首先新建一个工程,然后创建一个Actor蓝图,这里命名为“BP_TCPConnect” 打开“BP_TCPConnect”,添加如下节点: (1)当服务端与客户端断开连接时…

js-把对象的中文key转换为英文的key

// 原数据 const arrObj [{入职日期: 43535,姓名: 张三,工号: 9527,手机号: 13899999999,转正日期: 43719},{入职日期: 43535,姓名: 李四,工号: 9528,手机号: 18255555555,转正日期: 43719} ]// 转换-方式一 // results 是原数据async onSuccess ({ header, results }) {// …

JS-把并列的对象数组转为树状结构

// 将并列对象数组, 转换为树状结构 turnData(arr, pid){const newArr []arr.forEach(item > {if(item.pid pid){const children this.turnData(arr, item.id)if(children.length > 0){item.children children}newArr.push(item)}});return newArr }

JS-内存回收机制

什么是垃圾? 一般而言, 没有被引用的变量就是垃圾, 会被清除;有一个例外, 如果几个对象互相引用, 形成了一个闭环. 虽然有引用, 但是也是垃圾. 垃圾清除算法 标记清除-常用 会标记内存中存储的所有变量;然后&#xff0c;它会将所有在上下文中的变量&#xff0c;以及被在上下…