Vue3中Pinia的基本使用

Vue3中Pinia的基本使用

陈宇翔

Pinia 介绍

Pinia是一个专门为Vue.js设计的状态管理库,它提供了一种简单和直观的方式来管理应用程序的状态。在使用Pinia时,可以轻松地创建定义状态的存储,然后将其与Vue组件绑定,使它们能够使用该状态。和Vuex相比,Pinia 更加简单易用,体积更小,同时具有更好的 TypeScript 支持和插件系统。

安装和配置Pinia

安装和配置Pinia非常简单,像其他Vue插件一样,Pinia需要通过yarn或npm进行安装并且与Vue应用程序进行绑定,可以使用以下命令进行安装:

1
2
3
yarn add pinia
或者
npm install pinia

在安装完Pinia包之后,需要在main.js文件中导入createPinia函数并将Pinia插件与Vue应用程序绑定,如下所示:

1
2
3
4
5
6
7
8
9
10
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';

const pinia = createPinia(); // 创建Pinia实例
const app = createApp(App); // 创建根实例


app.use(pinia); // pinia插件的安装配置
app.mount('#app'); // 视图的挂载

使用 createPinia() 函数创建并初始化Pinia插件实例,将其与Vue应用程序绑定使用app.use(pinia)。至此,我们就可以使用Pinia来管理Vue应用程序的状态了。

语法糖写法-setup

  • 定义一个store
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { ref } from 'vue';
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter',()=> {

//数据(state)
const count = ref(10)

//修改数据的方法(action)
const increament=()=>{count.value++}

//getters写法
const doubleCount = computed(() => count.value * 2)

//记得要retuen
return{
count,
increament,
doubleCount
}
})
  • 在Vue组件中使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<template>

<!-- 这里使用store里的state -->
<div>{{ store.count }}</div>

<!-- 这里直接使用store里的getters -->
<div>{{ store.doubleCount() }}</div>

<!-- 这里使用store里的actions -->
<div @click="store.increament()"></div>

</template>

<script setup>

import {useCounterStore} from "../../store/counter.js";
const store = useCounterStore()

</script>

storeToRefs工具函数

注意,store 是一个用 reactive 包装的对象,这意味着不需要在 getters 后面写 .value。就像 setup 中的 props 一样,我们不能对它进行解构,如我们先前定义的counterStore仓库中的count和doubleCount,如果直接结构,那么再通过页面上的按钮进行加减时,页面将 不会实时更新

我们可以使用storeToRefs函数可以辅助保持数据(state + getter)的响应式解构:

1
2
3
4
5
//响应式数据丢失,视图不再更新
const { count,doubleCount } = counterStore

//保持数据响应式
const { count,doubleCount } = storeToRefs(counterStore)

Pinia持久化插件

官方文档:https://prazdevs.github.io/pinia-plugin-persistedstate/zh/

1.安装插件 pinia-plugin-persistedstate

1
npm i pinia-plugin-persistedstate

2.使用main.js

1
2
3
4
5
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

3.配置store/counter.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { ref } from 'vue';
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter',() => {

//数据(state)
const count = ref(10)

//修改数据的方法(action)
const increament=()=>{count.value++}

//getters写法
const doubleCount = computed(() => count.value * 2)

//记得要retuen
return{ count, increament, doubleCount }
}, {
persist: true,
},
)

4.其他配置,看官网文档即可。