Vuejs背景图片不起作用

时间:2018-07-07 03:32:46

标签: html css vue.js

大家好,

我在Vuejs中的背景图像样式中存在反斜线的问题,并且在HTML中无法替换字符串并解决问题。

检查元素的网址

http://localhost:8000/storage/banar-pages\July2018\WPNrFE6eXopKnjMqjNgW.jpg

从数据库

banar-pages\July2018\WPNrFE6eXopKnjMqjNgW.jpg

组件文件中的代码

<div class="block-entry fixed-background" :style="'background-image: url(' +link + '/storage/' + about.image +');'">
    <div class="container">
        <div class="row">
            <div class="col-sm-6 col-sm-offset-3">
                <div class="cell-view simple-banner-height text-center">
                    <div class="empty-space col-xs-b35 col-sm-b70"></div>
                    <h1 class="h1 light">{{ about.name }}</h1>
                    <div class="title-underline center"><span></span></div>
                    <div class="simple-article light transparent size-4">{{ about.details }}</div>
                    <div class="empty-space col-xs-b35 col-sm-b70"></div>
                </div>
            </div>
        </div>
    </div>
</div>

谢谢

2 个答案:

答案 0 :(得分:0)

您可以使用一种方法来处理该字符串并返回修改后的URL:

methods: {
    prepareURL(string) {
        return string.replace('/\\/g', '/');
    }
}

组件代码:

<div class="block-entry fixed-background" :style="'background-image: url(' +link + '/storage/' + prepareURL(about.image) +');'">
  <div class="container">
    <div class="row">
        <div class="col-sm-6 col-sm-offset-3">
            <div class="cell-view simple-banner-height text-center">
                <div class="empty-space col-xs-b35 col-sm-b70"></div>
                <h1 class="h1 light">{{ about.name }}</h1>
                <div class="title-underline center"><span></span></div>
                <div class="simple-article light transparent size-4">{{ about.details }}</div>
                <div class="empty-space col-xs-b35 col-sm-b70"></div>
            </div>
        </div>
    </div>
</div>

答案 1 :(得分:0)

  

我需要替换它的图像链接,但标记无效image.replace('/\\/g', '/')

您似乎错误地将字符串作为第一个参数传递给String#replace(),这将导致字面替换(即它将替换字符串中第一个出现的/\/g) :

console.log('XX/\\/gXX/\\/gXX'.replace('/\\/g', '/'))

将第一个参数的引号删除到make it a regular expression

console.log('\\path\\to\\foo.png'.replace(/\\/g, '/'))

然后,您的Vue模板可能与此类似:

<div :style="'background-image: url(' +link.replace(/\\/g, '/') + '/storage/' + about.image.replace(/\\/g, '/') +');'">

new Vue({
  el: '#app',
  data() {
    return {
      link: 'http:\\placekitten.com',
      about: {
        image: '\\100\\100'
      }
    }
  }
})
.dummy {
  width: 100px;
  height: 100px;
}
<script src="https://unpkg.com/vue@2.5.16"></script>

<div id="app">
  <div class="dummy"
       :style="`background-image: url(${link.replace(/\\/g, '/')}${about.image.replace(/\\/g, '/')})`">
  </div>
</div>