vue2中的状态管理是vuex,vue3使用的是pinia
- 安装pinia:
npm install pinia
- 在main.ts中引入pinia
import {createApp} from 'vue'; import App from './App.vue'; import {createPinia} from 'pinia'; const app = createApp(App); app.use(createPinia()); app.mount('#app');
- 创建store模块(store/sum.ts,组合式写法hooks函数)
// sum.ts import {defineStore} from 'pinia'; import {ref, computed} from 'vue'; export const useSumStore = defineStore('sum', () => {let sum = ref(0);function addSum() {if (sum.value < 10) {sum.value ++;}}const prefixSum = computed(() => {return '@@@' + sum.value;});return {sum, addSum, prefixSum}; });
- 在组件中使用(components/Sum/Sum.vue)
<template><div>总和为:{{sum}}</div><div>带前缀的总和为:{{prefixSum}}</div><button @click="add">+1</button> </template>
说明<script setup lang="ts"> import {useSumStore} from '@/store/sum.ts'; import {storeToRefs} from 'pinia'; const sumStore = useSumStore(); const {sum, prefixSum} = storeToRefs(sumStore); function add() {// 修改数据方式一// sumStore.sum += 1;// 修改数据方式二/* sumStore.$patch({sum: sum + 1})*/// 修改数据方式三,调用action函数sumStore.addSum(); } sumStore.$subscribe((mutate, state) => {console.log('store中存储的数据变化了', state); }); </script>
① 注意store/sum.ts中是hooks函数,要return相关属性
② storeToRefs作用同toRefs,防止丢失响应式
③ 修改store中数据有三种方法,一是直接修改,二是调用$patch批量修改,三是调用action函数修改
④ $subscribe类似watch,可以监听store中数据变化