VUE3中Pinia的使用

前言

Pinia 支持使用组合式 API 来定义 store,这种方式非常符合 Vue 3 的设计理念,尤其是在处理复杂逻辑时,组合式 API 提供了更好的代码组织和复用性。

安装与引用

安装

1
npm install pinia

main.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import "@/assets/css/_common.less"

import { createApp } from 'vue'
import { createPinia } from 'pinia'

import App from './App.vue'
import router from './router'

import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/reset.css';

const app = createApp(App)

app.use(createPinia())
app.use(router)
app.use(Antd)

app.mount('#app')

定义与使用

stores/common.ts

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

export const useCommonStore = defineStore('common', () => {
const loading = ref<boolean>(false)

function showLoading() {
loading.value = true
}

function hideLoading() {
loading.value = false
}

return { loading, showLoading, hideLoading }
})

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
<div>
<a-spin tip="数据获取中..." :spinning="loading">
</a-spin>
<button @click="showLoading">显示</button>
<button @click="hideLoading">隐藏</button>
</div>
</template>

<script setup>
import { useCommonStore } from '@/stores/common'
import { storeToRefs } from 'pinia'

const commonStore = useCommonStore()
const { loading } = storeToRefs(commonStore)
const { showLoading, hideLoading } = commonStore
</script>

无法显示Pinia调试工具

Vue3.0 vue.js.devtools无法显示Pinia调试工具

之前的配置方式:

1
2
3
app.use(createPinia())

app.mount('#app')

修改为:

1
app.use(createPinia()).mount("#app")

修改之后即可显示