<script setup> import { storeToRefs } from "pinia"; import {useAboutCompositionApiImplementStore,useAboutOptionsApiImplementStore } from "./stores/about.store"; // 组合式 const aboutCompositionApiStore = useAboutCompositionApiImplementStore(); // const {loading, aboutInfo} = storeToRefs(aboutCompositionApiStore); // 选项式 const aboutOptionsApiStore = useAboutOptionsApiImplementStore();</script> <template> <div>{{aboutCompositionApiStore.aboutInfo.data}}<button @click="aboutCompositionApiStore.loadAboutInfo()"> {{ aboutCompositionApiStore.loading ? 'Loading...' : 'Load Data' }}</button><button @click="aboutCompositionApiStore.reset()">reset</button> </div> <div>{{aboutOptionsApiStore.aboutInfo.data}}<button @click="aboutOptionsApiStore.loadAboutInfo()"> {{ aboutOptionsApiStore.loading ? 'Loading...' : 'Load Data' }}</button><button @click="aboutOptionsApiStore.reset()">reset</button> </div> </template>
import {defineStore} from "pinia"; import {ref, reactive} from 'vue' // 使用组合式API export const useAboutCompositionApiImplementStore =defineStore('aboutCompositionApi', () => {const loading = ref(false);const aboutInfo = reactive({data: []});const loadAboutInfo = async () => {try {loading.value = true;aboutInfo.data = await new Promise(resolve => {setTimeout(() => {resolve([{ id: 1, name: 'John Doe', role: 'CEO' },{ id: 2, name: 'Jane Smith', role: 'CTO' },{ id: 3, name: 'Mike Johnson', role: 'Developer' }])}, 1000)})} catch(e) {} finally {loading.value = false}}const reset = () => {loading.value = falseaboutInfo.data = []}return {loading,aboutInfo,reset,loadAboutInfo,} })// 使用选项式API export const useAboutOptionsApiImplementStore =defineStore('aboutOptionsApi', {state: () => ({loading: false,aboutInfo: {data: []}}),actions: {async loadAboutInfo() {try {this.loading = true;this.aboutInfo.data = await new Promise(resolve => {setTimeout(() => {resolve([{ id: 1, name: 'John Doe', role: 'CEO' },{ id: 2, name: 'Jane Smith', role: 'CTO' },{ id: 3, name: 'Mike Johnson', role: 'Developer' }]);}, 1000);});} catch (e) {console.error('加载失败:', e);} finally {this.loading = false;}},reset() {this.loading = false;this.aboutInfo.data = [];}} })