Pinia 快速入门
Pinia 是什么?
Pinia 是一个用于 Vue 的状态管理库,类似 Vuex, 是 Vue 的另一种状态管理方案
Pinia 支持 Vue2 和 Vue3
常见问题
关于该项目和可能问题的几点说明:
问:这是否取代了Vuex,是它的继任者吗?
答:不,或者至少这不是主要意图
问:动态模块呢?
答:动态模块不是安全的类型,因此我们允许创建不同的商店,可以在任何地方导入
Pinia 优势
符合直觉,易于学习
极轻, 仅有 1 KB
模块化设计,便于拆分状态
安装 Pinia
yarn add pinia@next
# or with npm
npm install pinia@next
用法
创建一个 pinia(根存储)并将其传递给应用程序:
import { createPinia } from 'pinia';
app.use(createPinia());
核心概念与基本使用
Store
Store 是一个保存状态和业务逻辑的实体,可以自由读取和写入,并通过导入后在 setup 中使用
创建一个 store
// store.js
import { defineStore } from "pinia";
interface MainState {
counter: number
name: string
}
export const useMainStore = defineStore({
// id: 必须的,在所有 Store 中唯一
id: "main",
// a function that returns a fresh state
state: () => MainState ({
counter: 0,
name: 'Eduardo',
}),
// optional getters
getters: {
doubleCount() {
return this.counter * 2
},
// use getters in other getters
doubleCountPlusOne() {
return this.doubleCount * 2 + 1
},
},
// optional actions
actions: {
reset() {
// `this` is the store instance
this.counter = 0
},
},
})
使用 Store
// xxx.vue
<template>
<div>
{{store.count}}
</div>
</template>
<script>
// 导入 Store, 使用自己的路径
import { useMainStore } from '@/stores/main'
export default defineComponent({
setup() {
// 调用函数 获得Store
const store = useMainStore()
return {
// gives access to the whole store
store,
// gives access only to specific state
state: computed(() => store.counter),
// gives access to specific getter; like `computed` properties
doubleCount: computed(() => store.doubleCount),
}
},
})
</script>
评论已关闭