vue动态绑定background的方法
作者:程琬清君
background是background-color,background-image,background-repeat,background-attachment,background-position,background-size等属性的缩写,本文我用动态绑定background-image来举例,感兴趣的朋友跟随小编一起看看吧
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,
    }
  }到此这篇关于vue动态绑定background的文章就介绍到这了,更多相关vue动态绑定background内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
