Pinia是什么?
Pinia问世已经很久了,最近搭建新的项目才知道有他,那么Pinia是干什么的呢?
Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。类似 Vuex, 是 Vue 的另一种状态管理方案。
与 Vuex 相比,Pinia 提供了一个更简单的 API,具有更少的规范,提供了 Composition-API 风格的 API,最重要的是,在与 TypeScript 一起使用时具有可靠的类型推断支持。
Pinia 同时支持 Vue2 和 Vue3
安装Pinia
使用自己习惯的包管理安装即可,我使用的是npm
npm install pinia
提示
根据官网说使用 Vue 2,还需要安装组合 API:@vue/composition-api。 使用 Nuxt,则应遵循 Nuxt的使用说明。我这里就不赘述,详情请参考官网。
创建Pinia并使用挂载
创建一个 pinia(根存储)并将其挂载在main.js
//src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
const pinia = createPinia()
const app = createApp(App);
app.use(pinia)
app.mount('#app')
基本使用
1、创建Store
store
-modules
-common.js
-index.js
index.js中引用modules中的分组管理的状态组
// src/store/index.js
import commonStore from './modules/common'
export {
commonStore,
}
modules中的js中定义保存各类需要使用的状态
// src/store/modules/common.js
import { defineStore } from 'pinia'
export default defineStore("common", {
state: () => ({
count: 0,
}),
getters: {
double: (state) => state.count * 2,
},
actions: {
setCount() {
console.log('this.count', this.count)
this.count++;
},
},
persist: {
key: 'COMMON_STORE',
storage: localStorage
}
});
2、Pinia数据持久化插件安装
当前代码中使用了数据持久化操作,这个需要安装Pinia的数据持久化插件 pinia-plugin-persist
npm install pinia-plugin-persist
3、挂载Pinia
将创建好的store挂载到main.js下
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
const app = createApp(App);
app.use(pinia)
app.mount('#app')
4、页面使用
<script setup>
import { ref } from 'vue'
import { commonStore } from '@/store'
const common = commonStore()
let count = ref(common.count)
// 订阅状态,状态值事件执行,页面状态值更新
common.$subscribe((even, value) => {
count.value = value.count
}, { detached: true })
const setCount = common.setCount
</script>
<template>
{{ count }}
</template>