开始

Pinia是Vue3的状态管理库,安装Pinia命令:npm i pinia

main.ts中引入Pinia

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

const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.mount('#app');

数据存储

在src目录下创建store目录,其中每个组件对应一个.ts文件,存储每个组件的响应式数据

定义数据存储store

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import {defineStore} from "pinia";

// 定义存储
// 传入一个字符串id,通常为组件名称
// 传入一个配置对象,定义state函数返回响应式数据
export const useCountStore = defineStore("count", {
state() {
return {
count: 0
}
},
// 使用箭头函数
// state: () => ({
// count: 0
// }),
});

使用store

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<script setup lang="ts">
import {ref} from 'vue';
import {useCountStore} from "@/store/count";

const countStore = useCountStore();

let n = ref(1);

// 使用存储中的ref数据时,不需要访问value
function add() {
countStore.count += n.value;
}

function sub() {
countStore.count -= n.value;
}
</script>

<template>
<div class="count">
<h2>当前求和为:{{countStore.count}}</h2>
<select v-model='n'>
<option :value="1">1</option>
<option :value="2">2</option>
<option :value="3">3</option>
</select>
<button @click="add">加</button>
<button @click="sub">减</button>
</div>
</template>

数据修改

  • 直接修改:直接获取数据进行修改

    1
    countStore.count += 1;
  • patch方法:通过$patch方法批量修改

    1
    2
    3
    countStore.$patch({
    count: 2,
    })
  • actions选项:在配置对象中设置actions选项,其中定义修改数据的方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import {defineStore} from "pinia";

    export const useCountStore = defineStore("count", {
    state() {
    return {
    count: 0
    }
    },
    actions: {
    // 通过this获取数据
    setCount(value: number) {
    this.count = value;
    }
    }
    });

    // 外部调用方法
    // countStore.setCount(2);

storeToRefs

将store中的响应式数据解构转换为ref类型

1
2
import {storeToRefs} from "pinia";
const {count} = storeToRefs(countStore)

getters选项

用于定义计算属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import {defineStore} from "pinia";

export const useCountStore = defineStore("count", {
state() {
return {
count: 0
}
},
getters: {
// 使用state参数获取数据
countPlus(state) {
return state.count + 1;
},
// 使用this获取数据,必须声明返回值类型或具有state形参
countMultiply(): number {
return this.count * 10;
}
}
});

$subscribe方法

$subscribe方法用于监视store中的数据变化

1
2
3
4
// 通过state参数获取变化后数据
countStore.$subscribe((mutation, state) => {
console.log(state.count);
})

组合式store

使用组合式写法定义store

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import {defineStore} from "pinia";

import {ref} from "vue";

// 箭头函数为setup函数
export const useCountStore = defineStore("count", () => {
// state
const count = ref(0);

// actions
function setCount(value: number) {
count.value = value;
}

// 返回数据或函数
return {
count,
setCount
}
});