vue3中使用vuex

vue3项目的搭建,如果是要用cli脚手架的话,那么需要先更新脚手架的版本,由于自己的版本不够,又不想去升级,所以我并没有选择cli,而是使用了vite;
如果是选择了vite,那么对于路由、vuex之类的就要自己安装引入了。
1.首先用vite创建vue3项目 npm create vite@latest

备注:

2.可以看到整个过程中是没有像cli一样可以直接把路由啊,仓库啊,什么exlint啊都直接选择安装到项目,所以接下来就要自己按需安装了。

安装vuex
npm install vuex@next --save
在src目录下创建一个文件夹,并创建一个ts文档
import { createStore } from 'vuex'
const store = createStore({
 state() {
   return {
     userInfo: {
       count: 100,
       name: '王美丽',
       age: 18,
     }
   }
 },
 mutations: {
   setUserInfo(state, { count, name, age }) {
     state.userInfo.count = count
     state.userInfo.name = name
     state.userInfo.age = age
   },
   hanldeUpdate(val) {
     console.log("调用更新")
   }
 },
 actions: {
 }
})
export default store
在main.js中引入
import store from "./store";
createApp(App).use(store).mount("#app");
在需要使用的页面中引入useStore
import { useStore } from "vuex";
可以在setup中验证一下
const storedata =useStore().state.goods;
console.log(storedata,'storedata')

3.vue2中我们经常会使用mapState,mapMutations等辅助函数,这样可以在页面使用的时候更加简洁,不需要$store.state.xxx
比如:

import { mapState,mapMutations } from "vuex";
computed: mapState(["state中某属性名"]),
然后就可以直接this.某属性名,愉快的使用了
在methods中使用 ...mapMutations(["mutations中的方法名"]),
然后就可以直接this.方法了

那vue3 是没有this的,也没有methods,这些咋用呢?
普通用法就是先定义后return出去
const storedata = useStore().state.要查的属性名;
如果也不想.state.xxx的话,那可以自定义一个hook函数,

import { computed } from 'vue'
import { mapState, useStore } from 'vuex'

export function useMapState(mapper) {
  // 拿到store独享
  const store = useStore()

  // 获取到对应的对象的functions: {name: function, age: function}
  const storeStateFns = mapState(mapper)

  // 对数据进行转换
  const storeState = {}
  Object.keys(storeStateFns).forEach(fnKey => {
    const fn = storeStateFns[fnKey].bind({ $store: store })
    storeState[fnKey] = computed(fn)
  })

  return storeState
}

在需要使用的页面先引入

import { useMapState } from "../hooks/useMapState";

然后就可以开始使用了

第一种方式不推荐使用:
const stateData = reactive(useMapState(["age","name","xxx",...]))
const age = stateData ['age']
const name = stateData ['name']
如果不想将ComputedRefImpl 转成 proxy 直接读取数据的话,后面要加value
useMapState(["age","name"])['age'].value

**还有一种方式,更加建议使用的,可以保证数据是响应式的**
const { userInfo } = useStore().state;
const age = computed(() => userInfo.age)

接下来说说mapMutations的使用

先展开后使用
<button @click="handleChange">点击修改身份信息</button>
const { commit } = useStore();
const resp = reactive({
      count: 2,
      name: "小白",``
      age: 1222,
});
const handleChange =()=>{
  commit("setUserInfo", resp);
}

最后看一下 mapActions吧,没空学习了,下次记录吧!

某博主封装方法
https://blog.csdn.net/qq_16139383/article/details/119935755

posted @   JocelynFung  阅读(149)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
Live2D 看板娘 / Demo
点击右上角即可分享
微信分享提示