在vue3中使用pinia(一)
参考中文官网如下:pinia.web3doc.top
一、在项目中安装pinia
npm i pinia
二、定义一个仓库
在store/index.js中定义仓库,并将仓库进行导出
import { defineStore } from 'pinia'
//第一个参数是应用程序中 store 的唯一 id
//默认命名规则user xxx Store,其中xxx为当前仓库的唯一id
export useMainSrote = defineStore('main',{
// 推荐使用 完整类型推断的箭头函数
state:()=>{
return{
// 所有这些属性都将自动推断其类型
name:'Jone',
age:18,
count:2
}
},
//我们可以在定义常规函数时通过 `this` 访问到 *整个 store 的实例*,但是在TS中需要定义返回类型
getters:{
},
actions:{
}
})
三、与main.js进行关联
在main.js中使用createPinia方法进行仓库导入
import { createPinia } from 'pinia'
//需要在创建App实例之后使用use
app.use(createPinia())
四、使用仓库
在.vue文件中使用仓库需要调用useStore方法来进行仓库导入
import { useMainSrote } from 'store文件路径'
import { toRefs } from 'vue'
//使用mainStore接收当前的useMainSrote实例
const mainStore = useMainStore()
//`store` 是一个用`reactive` 包裹的对象,这意味着不需要在getter 之后写`.value`
//但是,就像`setup` 中的`props` 一样,**我们不能对其进行解构**
//在对数据进行解构时,需要通过toRefs方法对数据进行保持响应式
const {name,age,count} = toRefs(mainStore)
console.log(main.age) // 18
在模板中使用仓库可以直接通过上述方式直接访问
<template>
<div ref="divRef">
{{main.age}}
</div>
</template>
四、订阅状态
通过store的$subscribe()可以对仓库状态进行查看状态及其变化
//可以监听到state的变化
//以下用来实现本地存储
mainStore.$subscribe((mutations,state)=>{
localStorage.setItem('store',JSON.stringify(state))
})