Pinia 初始
介绍
- 完整的
ts的支持; - 足够轻量,压缩后的体积只有
1kb左右; - 去除
mutations,只有state,getters,actions; actions支持同步和异步;- 代码扁平化没有模块嵌套,只有
store的概念,store之间可以自由使用,每一个store都是独立的 - 无需手动添加
store,store一旦创建便会自动添加; - 支持
Vue3和Vue2;
- 完整的
安装
npm install pinia1yarn add pinia1// Make sure to add code blocks to your code group
创建一个
pinia(根存储)并将其传递给应用程序:import { createPinia } from 'pinia' const store = createPinia() app.use(store)1
2
3
4import { createPinia, PiniaVuePlugin } from 'pinia' Vue.use(PiniaVuePlugin) const pinia = createPinia() new Vue({ el: '#app', // 其他选项... // ... // 注意同一个pinia实例可以在多个 Vue 应用程序中使用 // 同一个页面 pinia, })1
2
3
4
5
6
7
8
9
10
11
12
13// Make sure to add code blocks to your code group
初始化
store新建文件
store-name.ts,存储是使用定义的defineStore(),并且它需要一个唯一的名称,作为第一个参数传递。export const enum Names { Test = 'TEST' }1
2
3新建一个文件
store/index.tsimport { defineStore } from 'pinia' import { Names } from './store-name' // 这个名称,也称为id,是必要的,Pania使用它来将商店连接到devtool。将返回的函数命名为use...是可组合项之间的约定,以使其使用习惯。 export const useTestStore = defineStore(Names.Test, { })1
2
3
4
5
6
7定义仓库
storeimport { defineStore } from 'pinia' import { Names } from './store-name' export const useTestStore = defineStore(Names.Test, { // State 箭头函数 返回一个对象 在对象里面定义值 state:()=>{ return { current:1 } }, //类似于computed 可以帮我们去修饰我们的值 getters:{ }, //可以操作异步 和 同步提交state actions:{ } })1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
上次更新: 2025/06/23, 07:26:12