[Vuejs]-Vuejs background image not work

0πŸ‘

βœ…

I need to replace image link it but flage not work image.replace('/\\/g', '/')

It looks like you’re incorrectly passing a string as the first argument to String#replace(), which would result in a literal replacement (i.e., it would replace the first occurrence of /\/g in the string):

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

Remove the quotes from the first argument to make it a regular expression:

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

Then, your Vue template could be similar to this:

<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>

0πŸ‘

You could have a method for processing that string and returning a revised URL:

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

Component code:

<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>

Leave a comment