【发布时间】:2021-08-28 14:30:33
【问题描述】:
有没有办法根据条件更改背景图像?
我正在尝试构建一个天气应用程序,我将更改 div 的背景。 喜欢:
天气 api 返回:
- rainy -> 将背景图片更改为rain.jpg
- snow -> 将背景图片更改为 snow.jpg
- sunny -> 将背景更改为sunny.jpg
- 等
我已经尝试了多种方法,但没有任何效果。
【问题讨论】:
标签: css vue.js conditional-statements styles
有没有办法根据条件更改背景图像?
我正在尝试构建一个天气应用程序,我将更改 div 的背景。 喜欢:
天气 api 返回:
我已经尝试了多种方法,但没有任何效果。
【问题讨论】:
标签: css vue.js conditional-statements styles
<template>
<div :class="{background_image}"></div>
</template>
<script>
export default {
// ...
data() {
return {
backgroundImage: 'snow'
},
computed:{
background_image : function () {
switch(this.backgroundImage) {
case 'snow':
return 'bg-snow';
case 'rainy':
return 'bg-rainy';
case 'sunny':
return 'bg-sunny';
default:
return 'bg-default';
}
}
},
methods: {
apiCall() {
//api call update background image according to the response
this.backgroundImage = response ; // response contains sunny text
}
},
// ...
}
</script>
<style>
.bg-sunny{
background-image: url('sunny.jpg');
}
.bg-snow{
background-image: url('snow.jpg');
}
.bg-rainy{
background-image: url('rainy.jpg');
}
.bg-default{
background-image: url('default.jpg');
}
</style>
【讨论】:
您可以通过在对象中查找图像来实现此行为,您已在其中定义了键和相应的图像值。此外,您需要告诉 webpack 需要该媒体文件。 require 告诉 webpack 将此文件视为请求。
<template>
<div :style="{ backgroundImage: `url(${weatherTypes[getWeatherType()]})` }"></div>
</template>
<script>
export default {
// ...
data() {
return {
weatherTypes: {
snow: require('some/path/snow.png'),
sun: require('some/path/sun.png'),
// ...
}
}
},
methods: {
getWeatherType() { return 'snow'; },
},
// ...
}
</script>
【讨论】: