src\pages\demo.vue
<template>
<div :style="{ backgroundImage: `url(${randomBackgroundUrl})` }"></div>
</template>
<script setup lang="ts">
import { useBackgroundStore } from "@/stores/backgroundStore";
const backgroundStore = useBackgroundStore();
const randomBackgroundUrl = computed(
() => backgroundStore.getCurrentBackgroundUrl
);
onMounted(() => {
if (!backgroundStore.getCurrentBackgroundUrl) {
backgroundStore.setRandomBackground();
}
});
</script>
src\stores\backgroundStore.ts
// stores/backgroundStore.ts
import { defineStore } from 'pinia';
export const useBackgroundStore = defineStore('background', {
state: () => ({
backgroundUrls: [
"https://demo.com/001.webp",
"https://demo.com/002.webp",
"https://demo.com/003.webp",
// 其他在线图片url...
],
randomBackgroundUrl: '',
}),
actions: {
setRandomBackground() {
const randomIndex = Math.floor(Math.random() * this.backgroundUrls.length);
this.randomBackgroundUrl = this.backgroundUrls[randomIndex];
},
setBackgroundUrl(url: string) {
this.randomBackgroundUrl = url;
},
},
getters: {
getCurrentBackgroundUrl: (state) => state.randomBackgroundUrl,
},
});