- 步骤一:创建响应式数据来存储背景图片的 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>
- 步骤一:在
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>
<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>