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()
就是getters
function()
就是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…