最近想复习一下vue,就准备写一个后台练练手,开始写登陆页面时,感觉单一背景太单调了,就想着写一个动态切换的背景登录页,可是发现虽然变量定义了,效果却没实现,图片不显示,下面展示一下成功,以及错误代码,和正确代码
运行效果
错误代码
<template>
<div id="login" :style="{backgroundImage:`url(${loginImage})`}">
<div class="isbtn" @click="change()">切换主题</div>
</div>
</template>
<script>
export default {
name: '',
data() {
return {
imgindex:1,
loginImage:('../assets/bgimg/5.jpg')
};
},
computed:{
},
watch:{
},
methods: {
change(){
if(this.imgindex<10){
this.imgindex+=1
console.log(this.imgindex)
}else{
this.imgindex=1
}
this.loginImage=(`../assets/bgimg/${this.imgindex}.jpg`)
}
},
};
</script>
<style scoped lang="scss">
.isbtn{
position: fixed;
top: 50px;
right: 40px;
// background: red;
color: #0aa1ed;
// background: lightsalmon;
font-size: 14px;
padding: 5px;
opacity: 0.8;
cursor: pointer;
}
#login {
width: 100vw;
height: 100vh;
overflow: hidden;
position: relative;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;
}
</style>
正确代码 后来查了查发现如果想要动态引入本地图片的话,需要加一个require引入,不然引入路径是一个字符串,不会被识别出来,具体可以再开发者模式看看有啥区别
<template>
<div id="login" :style="{backgroundImage:`url(${loginImage})`}">
<div class="isbtn" @click="change()">切换主题</div>
</div>
</template>
<script>
export default {
name: '',
data() {
return {
imgindex:1,
loginImage:require('../assets/bgimg/5.jpg')
};
},
computed:{
},
watch:{
},
methods: {
change(){
if(this.imgindex<10){
this.imgindex+=1
console.log(this.imgindex)
}else{
this.imgindex=1
}
this.loginImage=require(`../assets/bgimg/${this.imgindex}.jpg`)
}
},
};
</script>
<style scoped lang="scss">
.isbtn{
position: fixed;
top: 50px;
right: 40px;
// background: red;
color: #0aa1ed;
// background: lightsalmon;
font-size: 14px;
padding: 5px;
opacity: 0.8;
cursor: pointer;
}
#login {
width: 100vw;
height: 100vh;
overflow: hidden;
position: relative;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;
}
</style>