【问题标题】:Vue dynamic background image inline componentVue动态背景图片内联组件
【发布时间】:2020-07-06 15:12:58
【问题描述】:

我正在使用 Vue 构建一个需要动态背景的横幅,但是它似乎不起作用。不知道我做错了什么。我尝试了其他一些方法,如果我做一个类似的图像标签,它就可以工作

<img :src="require(`@/assets/images/${backgroundImage}`)" />

但显然这需要是内嵌背景图片。

代码:

组件

<template>
  <div
    class="w-full h-64 bg-auto bg-no-repeat bg-center lg:bg-cover relative"
    :style="{ backgroundImage: url(require('@/assets/images/' + backgroundImage))}"
  >
    <div class="w-full h-full flex flex-col justify-center items-center text-white px-6">
      <div class="hero-text rounded text-center py-8 px-12">
        <p class="text-base lg:text-md uppercase font-medium">{{ smallLeadingText }}</p>
        <h1 class="text-xl md:text-3xl lg:text-5xl uppercase font-bold">{{ mainText }}</h1>
        <p class="text-base lg:text-md">{{ subText }}</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "PageHero",
  props: {
    backgroundImage: String,
    smallLeadingText: {
      type: String,
      required: false
    },
    mainText: {
      type: String,
      required: true
    },
    subText: {
      type: String,
      required: false
    }
  }
};
</script>

查看

<PageHero
  backgroundImage="mc-background.png "
  smallLeadingText="Powerful, secure &amp; affordable"
  mainText="Minecraft hosting"
  subText="Plans suitable for all budgets"
/>

【问题讨论】:

标签: javascript css vue.js vue-component


【解决方案1】:

看起来您的 style 属性中围绕字符串引用出现了一些语法错误。试试

<div :style="{ backgroundImage: `url(${require('@/assets/images/' + backgroundImage)})` }">

创建一些计算属性来解决所有问题可能会更容易

computed: {
  bgImage () {
    return require('@/assets/images/' + this.backgroundImage)
  },
  inlineStyle () {
    return {
      backgroundImage: `url(${this.bgImage})` 
    }
  }
}

<div :style="inlineStyle">

演示~https://codesandbox.io/s/crimson-sky-ehn9r

【讨论】:

  • 所以我尝试了您的代码,但如果我删除了代码显示的 :style,即使使用计算的路线,它也会删除代码 gyazo.com/09f006c0bdef02156051924a9f30037b。
  • 两个示例的相同问题只是将组件显示为注释&lt;---&gt;,实际上并没有显示style绑定。
  • @debugabug 适合我。我添加了一个演示链接
  • 嘿,这是一个关于正在发生的事情的小视频,不知道为什么,鉴于示例链接,一切都是正确的。 i.gyazo.com/91d584adb32ef0f148e1a13397b3c1d6.mp4
  • @debugabug 您的浏览器控制台中有三个错误。它们是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-04
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
  • 2018-11-09
  • 2019-07-31
相关资源
最近更新 更多