新一代状态管理工具,Pinia.js 上手指南

程序员成长指北

共 4419字,需浏览 9分钟

 · 2022-02-26

大厂技术  高级前端  Node进阶

点击上方 程序员成长指北,关注公众号

回复1,加入高级Node交流群


前言

Pinia.js 是新一代的状态管理器,由 Vue.js团队中成员所开发的,因此也被认为是下一代的 Vuex,即 Vuex5.x,在 Vue3.0 的项目中使用也是备受推崇。

Pinia.js 有如下特点:

  • 完整的 typescript 的支持;
  • 足够轻量,压缩后的体积只有1.6kb;
  • 去除 mutations,只有 state,getters,actions(这是我最喜欢的一个特点);
  • actions 支持同步和异步;
  • 没有模块嵌套,只有 store 的概念,store 之间可以自由使用,更好的代码分割;
  • 无需手动添加 store,store 一旦创建便会自动添加;

安装

npm install pinia --save
复制代码

创建 Store

新建 src/store 目录并在其下面创建 index.ts,导出 store

// src/store/index.ts

import { createPinia } from 'pinia'

const store = createPinia()

export default store
复制代码

在 main.ts 中引入并使用。

// src/main.ts

import { createApp } from 'vue'
import App from './App.vue'
import store from './store'

const app = createApp(App)
app.use(store)
复制代码

State

定义State

在 src/store 下面创建一个user.ts

//src/store/user.ts

import { defineStore } from 'pinia'

export const useUserStore = defineStore({
  id'user'// id必填,且需要唯一
  state() => {
    return {
      name'张三'
    }
  }
})

复制代码

获取 state