pinia用法和vue用法一样,有两种。一种是options用法,一种是setup用法。options 用法是我们常用的方法,本文就不多介绍,主要介绍第二种用法 —— setup用法。具体用法如下:
一、安装依赖包
pinia主依赖包pinia-plugin-persistedstate数据持久化依赖包
yarn add pinia pinia-plugin-persistedstate
二、在main.ts文件中引入依赖包
必须在main.ts 中引入并设置 pinia 和 pinia-plugin-persistedstate ,才能在项目中正常使用,具体设置如下:
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { createPersistedState } from 'pinia-plugin-persistedstate'
import App from './App.vue'
const app = createApp(App)
const pinia = createPinia()
pinia.use(
createPersistedState({
auto: true
})
)
app.use(pinia)
app.use(router)
app.mount('#app')
三、创建 pinia stores
就用官方计数器举例,在stores文件夹下,创建一个counter.ts文件:
import { ref, computed, reactive } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore(
'counter',
() => {
const count = ref(1)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
},
// 持久化设置 带选项设置
{
persist: {
key: 'counter',
paths: ['count']
},
},
// 持久化设置 简易设置
// {
// persist:true
// }
)
上例是采用
setup stores写法,看上去和vue中的hooks写法基本相同。
pinia 的setup写法和options写法类比 :
ref()就是state属性computed()就是gettersfunction()就是actions。
setup写法比options写法更灵活,一般推荐setup写法,具体看个人喜好。
持久化设置:
- 简易设置:
persist:true即可 - 带选项设置:可以分别设置
key( 用于引用storage中的数据,string类型)、storage(storage类型,可设置为localStorage和sessionStorage两种,默认值为localStorage)、paths(用于指定state中哪些数据需要被持久化,类型为string[]数组) 等。
四、在组件中使用
在组件中使用pinia stores非常简单,具体如下:
<script setup lang="ts">
import { useCounterStore } from '@/stores/counter'
import { storeToRefs } from 'pinia';
// 用解构方式使用时,需要用 storeToRefs 包裹一层
const { count, doubleCount } = storeToRefs(useCounterStore())
const { increment } = useCounterStore()
</script>
<template>
<main>
<div>
<p>count: {{ count }}</p>
<p>doubleCount: {{ doubleCount }}</p>
<div><button @click="increment">add</button></div>
</div>
</main>
</template>
需要注意的是在用解构方式使用state数据时(用ref(),reactive(),computed()定义的数据),需要用storeToRefs 把数据再包裹一层,否则会失去响应式。
如果不想用storeToRefs包裹的话,就直接使用,不要解构,示例如下:
<script setup lang="ts">
import { useCounterStore } from '@/stores/counter'
const counterStore = useCounterStore()
</script>
<template>
<main>
<div>
<p>count: {{ counterStore.count }}</p>
<p>doubleCount: {{ counterStore.doubleCount }}</p>
<div><button @click="counterStore.increment">add</button></div>
</div>
</main>
</template>
这种方式看上去代码比较臃肿,特别是数据比较多的时候推荐用解构方式进行编码。
五、结束语
关于pinia setup store及数据持久化的简单用法就介绍这些,其它深入用法各位看官查看官网文档自行探索。
pinia文档:pinia.vuejs.org/
pinia-plugin-persistedstate文档:prazdevs.github.io/pinia-plugi…