vuex有几个属性及作用

vuex是vue的状态管理工具,用来管理项目中的公共数据能够在所有的组件中使用,一共有五大核心
state存放公共数据的地方通过this.$store.state.xxx调用,调用的时候会通过计算属性computed把state,return出去再用
mutations修改state的地方只有这里能修改state通过this.$store.commit调用
getters相当于是之前的计算属性通过this.$store.getters调用
actions执行异步操作的地方通过this.$store.dispatch调用
modules模块化    每一个modules 里面都包含其他四大核心

vuex 缺点就是刷新数据会丢失 我们可以保存本地存储 或者 安装 vuex 持久化插件 vuex-persist 去实现自动本地存储

vuex的执行机制:先在页面中通过 this.$store.dispatch 调用 action 再在 actions 中通过 commit 触发 mutations 方法

vuex的辅助函数是vuex的语法糖
mapState和mapGetters展开在计算属性里
mapMutation和mapAction 展开在方法里
用的时候都先 import 引入
import { mapState, mapMutations } from "vuex";

computed: {
    // name() {
    //   return this.$store.state.name;
    // },

    ...mapState(["name", "age"]),
  },
  methods: {
    // change() {
    //   this.$store.commit("change")
    // },
    ...mapMutations(["change"]),
    //调用mutation修改name
  },
  
  modules怎么使用?
当vuex里数据很多的时候我们可以分模块管理数据建立不同的js文件作为我们的模块文件,每一个模块里都有 state 等其他的四大核心,把这个js文件引入到 store/index.js 中 在 modules 中注册,使用模块里的数据的时候
this.$store.state.xx(模块名字).arr(state 数据名字)
如果使用模块里的 mutations 方法
首先在模块里跟 state 同级的地方开启一个命名空间 namespaced:true
使用的时候 this.$store.commit("a(模块名字)/add(模块里方法的名字)")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vuex 中,有四个常用的辅助函数可以简化对 store 中状态的访问和操作: 1. `mapState`:将 store 中的状态映射为组件的计算属性。它接收一个数组或对象作为参数,数组中的字符串为 state 的属性名,或者对象中的键值对为计算属性的名字和 state 的属性名。例如: ```javascript import { mapState } from 'vuex'; export default { computed: { ...mapState(['count']) // 将 store 中的 count 状态映射为组件的计算属性 } } ``` 2. `mapGetters`:将 store 中的 getters 映射为组件的计算属性。它接收一个数组或对象作为参数,用法与 `mapState` 类似。例如: ```javascript import { mapGetters } from 'vuex'; export default { computed: { ...mapGetters(['doubleCount']) // 将 store 中的 doubleCount getter 映射为组件的计算属性 } } ``` 3. `mapMutations`:将 store 中的 mutations 映射为组件的方法。它接收一个数组或对象作为参数,数组中的字符串为 mutations 的方法名,或者对象中的键值对为方法名和 mutations 的方法名。例如: ```javascript import { mapMutations } from 'vuex'; export default { methods: { ...mapMutations(['increment']) // 将 store 中的 increment mutation 映射为组件的方法 } } ``` 4. `mapActions`:将 store 中的 actions 映射为组件的方法。它接收一个数组或对象作为参数,用法与 `mapMutations` 类似。例如: ```javascript import { mapActions } from 'vuex'; export default { methods: { ...mapActions(['asyncAction']) // 将 store 中的 asyncAction action 映射为组件的方法 } } ``` 通过使用这些辅助函数,可以简化在组件中访问和操作 store 中状态、getters、mutations 和 actions 的代码,提高开发效率和代码可读性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值