开始
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";
export const useCountStore = defineStore("count", { state() { return { 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>
|
数据修改
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: { countPlus(state) { return state.count + 1; }, countMultiply(): number { return this.count * 10; } } });
|
$subscribe方法
$subscribe方法用于监视store中的数据变化
1 2 3 4
| 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";
export const useCountStore = defineStore("count", () => { const count = ref(0);
function setCount(value: number) { count.value = value; } return { count, setCount } });
|