VUE3 script setup里面如何动态更新整个页面的背景图片
1. 使用内联样式和响应式数据
<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 变量(更灵活的方式)
<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>