Vue3+Pinia: 每次加载页面时,随机请求网络图片作为背景

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,
  },
});
暂无评论

发送评论 编辑评论


				
上一篇
下一篇