前言
Pinia 支持使用组合式 API 来定义 store,这种方式非常符合 Vue 3 的设计理念,尤其是在处理复杂逻辑时,组合式 API 提供了更好的代码组织和复用性。
安装与引用
安装
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
| <template> <div> <a-spin tip="数据获取中..." :spinning="loading"> </a-spin> </div> </template>
<script setup> import { useCommonStore } from '@/stores/common' import { storeToRefs } from 'pinia'
const commonStore = useCommonStore() const { loading } = storeToRefs(commonStore) </script>
|
其他页面使用
1 2 3 4 5 6 7 8 9 10 11 12
| <template> <div> <button @click="showLoading">显示</button> <button @click="hideLoading">隐藏</button> </div> </template>
<script setup> import { useCommonStore } from '@/stores/common' const commonStore = useCommonStore() const { showLoading, hideLoading } = commonStore </script>
|
两种使用方式
直接解构
响应性丢失
1 2 3 4 5 6 7 8 9 10 11 12
| <template> <div> {{ commonStore.loading }} </div> </template>
<script setup> import { useCommonStore } from '@/stores/common' const commonStore = useCommonStore() const { loading, showLoading, hideLoading } = commonStore </script>
|
保持响应性
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <template> <div> <label> <input type="checkbox" v-model="loading" /> 加载中:{{ loading }} </label> </div> </template>
<script setup> import { useCommonStore } from '@/stores/common' const commonStore = useCommonStore() const { loading } = storeToRefs(commonStore) </script>
|
无法显示Pinia调试工具
Vue3.0 vue.js.devtools无法显示Pinia调试工具
之前的配置方式:
1 2 3
| app.use(createPinia())
app.mount('#app')
|
修改为:
1
| app.use(createPinia()).mount("#app")
|
修改之后即可显示