刚开始使用vue3的时候,全局状态管理器都是使用pinia。还没去了解的时候并不明白为什么要换掉vuex,毕竟是用了好几年的状态管理器,能达到的效果和语法跟vuex几乎一模一样,所以为什么要换?
当时创建模板项目的也没说清楚,就说是vue3团队推荐使用的,大家都在用,那就用吧。其实并不喜欢这样的答案,大家都用那就用。
去官网看看,去Vuex GitHub看看,这不就是vuex5吗,只是换了个名字。
Pinia is now the new default
The official state management library for Vue has changed to Pinia. Pinia has almost the exact same or enhanced API as Vuex 5, described in Vuex 5 RFC. You could simply consider Pinia as Vuex 5 with a different name. Pinia also works with Vue 2.x as well.
Vuex 3 and 4 will still be maintained. However, it's unlikely to add new functionalities to it. Vuex and Pinia can be installed in the same project. If you're migrating existing Vuex app to Pinia, it might be a suitable option. However, if you're planning to start a new project, we highly recommend using Pinia instead.
你可以简单地将 Pinia 视为具有不同名称的 Vuex 5。所以,相同的团队,相同的功能,就是换个名字。
肯定也有一些人用习惯了某个插件,心里还是有点排斥升级,完全没必要,使用方法几乎一模一样,而且更符合vue3,也兼容vue2.x,所以早点拥抱pinia吧。
安装:npm install pinia
main.js注入:
import { createPinia } from "pinia";
const pinia = createPinia();
app.use(pinia);
创建store文件夹,如果分模块就个自新建自己的.ts文件:common.ts、goods.ts,也可以一个文件里面通过不同名字区分:
import { defineStore } from 'pinia'
export const commonStore = defineStore('common', {
state: () => {
return {
name: 'common'
};
},
actions: {
saveName(name: string) {
this.name = name;
},
},
})
使用:
<template>
{{ store.name }}
</template>
<script setup lang="ts">
import { commonStore } from "../store/common";
const store = commonStore();
setTimeout(() => {
store.saveName("wade");
}, 3000);
</script>
跟vuex真的一样,其它使用就不举例了,可以官网好好看看。
倒是几个API可以注意一下:
所以,拥抱大菠萝pinia吧,只是新一代的vuex。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有