VUE3 script setup里面如何动态更新整个页面的背景图片

1. 使用内联样式和响应式数据


  • 步骤一:创建响应式数据来存储背景图片的 URL
    script setup中,可以使用ref来创建一个响应式的变量来存储背景图片的 URL。
<template>
  <div>
    <button @click="changeBackground">更换背景图片</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
const backgroundImageUrl = ref('your_initial_image_url.jpg');

const changeBackground = () => {
  // 这里可以是根据某种逻辑来选择新的图片 URL,比如从一个数组中选择下一个
  backgroundImageUrl.value = 'new_image_url.jpg';
};
</script>

<style scoped>
div {
  width: 100%;
  height: 100vh;
  background-image: url({{ backgroundImageUrl.value }});
  background-size: cover;
  background-position: center;
}
</style>

 

2. 使用 CSS 变量(更灵活的方式)

    • 步骤一:在script setup中定义 CSS 变量和更新函
<template>
  <div>
    <button @click="changeBackground">更换背景图片</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
const root = document.documentElement;
const backgroundImageUrl = ref('your_initial_image_url.jpg');

const changeBackground = () => {
  backgroundImageUrl.value = 'new_image_url.jpg';
  root.style.setProperty('--background-image-url', `url(${backgroundImageUrl.value})`);
};

onMounted(() => {
  root.style.setProperty('--background-image-url', `url(${backgroundImageUrl.value})`);
});
</script>

<style scoped>
div {
  width: 100%;
  height: 100vh;
  background-image: var(--background-image-url);
  background-size: cover;
  background-position: center;
}
</style>

3. 结合 Vue 的动态绑定类或样式(如果有多个样式变化情况)

 

  • 步骤一:定义多个样式类和数据来控制样式切换
<template>
  <div :class="['page', backgroundClass]">
    <button @click="changeBackground">更换背景图片</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
const backgroundClass = ref('bg-image-1');

const changeBackground = () => {
  backgroundClass.value = 'bg-image-2';
};
</script>

<style scoped>
.page {
  width: 100%;
  height: 100vh;
}
.bg-image-1 {
  background-image: url(image1.jpg);
  background-size: cover;
  background-position: center;
}
.bg-image-2 {
  background-image: url(image2.jpg);
  background-size: cover;
  background-position: center;
}
</style>

 

 

 

posted @ 2024-11-11 18:19  lytcreate  阅读(25)  评论(0编辑  收藏  举报