1.pinia的介绍
2.安装并创建pinia
3.使用pinia的实例
4.Pinia 构建用户仓库 和持久化
目录
1.pinia的介绍
pinia简单来说就是vue的状态管理库(允许跨组件)
2.
安装pinia
yarn add pinia
# 或者使用 npm
npm install pinia
若你下载了pnpm包管理器(使用这个包管理器比较快),则为
pnpm install pinia
创建pinia
这些事做完了就可以创建并使用了。
3.pinia的使用
Store 是用 defineStore() 定义的,它的第一个参数会被作为id,必须得传
import { defineStore } from "pinia";
import { ref } from "vue";
import { computed } from "vue";
// defineStore(仓库的唯一标识,()=>{....})
export const useTheStore = defineStore("counter",()=>{
//声明数据
const count = ref(100)
const msg = ref("hi pinia")
//声明操作数据的方法 action(普通函数)
const addCount = ()=>{
count.value+=10
}
const subCount = ()=>{
count.value-=10
}
//声明基于数据派生的计算属性 getter (computed)
const double = computed(()=>{return count.value*2})
return{
addCount,
subCount,
double,
count,
msg,
}
})
你定义的数据和方法写完后记得return出去,不然外面的拿不到。
<script setup lang="ts">
import { useTheStore } from '../store/pinia'
const storeCount = useTheStore()
</script>
<template>
<div>
<p>pinia - {{ storeCount.count }} - {{ storeCount.msg }} - {{ storeCount.double }}</p>
<button @click="storeCount.subCount">-</button>
<button @click="storeCount.addCount">+</button>
</div>
</template>
<style scoped>
</style>
如果你嫌写storeCount.addCount太麻烦,就可以通过使用storeToRefs进行解构(若不适用storeToRefs,数据将丢失响应式),方法不需要使用storeToRefs便可直接解构
<script setup lang="ts">
import { useTheStore } from '../store/pinia'
//对于pinia中拿来数据若直接解构,不处理,数据就会丢失响应式
//此时需使用storeToStore
import { storeToRefs } from 'pinia'
const storeCount = useTheStore()
const {count} = storeToRefs(storeCount)
//对于pinia的方法则可直接解构
const {addCount} = storeCount
//pinia 的持久化 ----个人感觉和js的localStorage差不多
</script>
<template>
<div>
<p>pinia - {{ storeCount.count }} - {{ storeCount.msg }} - {{ storeCount.double }}</p>
<button @click="storeCount.subCount">-</button>
<button @click="storeCount.addCount">+</button>
<p>我是pinia中的 - {{ count }}</p>
<button @click="addCount">(我是pinia中的button) + </button>
</div>
</template>
<style scoped>
</style>
4.Pinia 构建用户仓库 和 持久化(刷新之后数据仍在)
安装依赖:
pnpm add pinia-plugin-persistedstate -D
将插件添加到实例上:
import { createApp } from 'vue'
import { createPinia } from "pinia"
import persist from 'pinia-plugin-persistedstate'
import App from './App.vue'
const app = createApp(App)
app.use(createPinia().use(persist))
app.mount("#app")
用法:
export const userStore = defineStore("myname",()=>{
const token = ref("")
const setToken = (newToken:any) => {
token.value = newToken
}
const removeToken = () =>{
token.value = ""
}
return {
token,
setToken,
removeToken
}
},{
persist:true // 为true时整个 Store 将使用默认持久化配置保存,其也可为对象(自己设置配置)
})