首页 前端知识 vue动态绑定background

vue动态绑定background

2024-04-08 11:04:02 前端知识 前端哥 126 951 我要收藏

background是background-color,background-image,background-repeat,background-attachment,background-position,background-size等属性的缩写。

这篇文章我用动态绑定background-image来举例。

我们都知道普通的css中写background-image是这样的:

background-image: url("./登录页bg.png");
复制

但在vue中用style写background-image时无法显示:

<div class="login-container" style="{ background-image: url("./登录页bg.png")}"></div>
复制

为什么呢?答:因为这样写url会被解析成字符串,取不出来,所以需要动态的绑定,以下有三种写法:

写法一:

<div class="login-container"
:style="{ backgroundImage: `url(${require('./登录页bg.png')})` }">
</div>
复制

写法二:

<div
class="login-container"
:style="{
backgroundImage: loginBackEcho.fileContext
? `url(${loginBackEcho.fileContext})`
: `url(${loginUrl})`,
}"
></div>
// 简写script:
props: {
loginBackEcho: {
type: Object,
default: () => {},
},
},
data() {
return {
loginUrl: require("./登录页bg.png"),
};
}
复制

写法三:

<div
class="login-container"
:style="{ backgroundImage: `url(${imgss})` }"
></div>
// 简写script:
import imgss from "./登录页bg.png";
data() {
return {
imgss: imgss,
}
}
复制

转载请注明出处或者链接地址:https://www.qianduange.cn//article/4583.html
标签
评论
还可以输入200
共0条数据,当前/页
发布的文章

JQuery中的load()、$

2024-05-10 08:05:15

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!