Home > Net >  my background-image property is not concatenating properly
my background-image property is not concatenating properly

Time:11-05

I have some code I am using with vuejs that binds a domain as well as an additional snippet that should get added to the domain. I cant seem to figure out the proper concatenation when it comes to the domain and item.url

var vm = new Vue({
        el: '#app',
        data: {
           items:[],
          domain:"https://example.com/"
        },
           
         },
        mounted: function () {
           
            })
        },
        
        })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id ="app">
<div v-for="item in items" class="gallery-cell" v-bind:style="{ backgroundImage: 'url('  domain   item.url   ')' }">{{ item.text}}</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Your Vue declaration is a total mess.
After fixing it background image is concatenated as it should

new Vue({
    el: '#app',
    data: {
        items: [
            { text: 'test1', url: 'ac0/cat-1364386.jpg' },
            { text: 'test2', url: '867/volcanic-mt-ngauruhoe-1378772.jpg' },
            { text: 'test3', url: '981/cow-1380252.jpg' }
        ],
        domain: "https://images.freeimages.com/images/large-previews/"
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <div v-for="item in items"
         v-bind:style="{ backgroundImage: 'url('  domain   item.url   ')' }"
         class="gallery-cell">
        {{ item.text }}
    </div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I would highly recommend to use template strings for better readability. And it's recommended to use a method and not doing your background image path building within your template.

new Vue({
  el: '#app',
  data: {
    items: [
      { text: 'a', url: '10096730/pexels-photo-10096730.jpeg' },
      { text: 'b', url: '9772527/pexels-photo-9772527.jpeg' },
    ],
    domain: 'https://images.pexels.com/photos/'
  },
  methods: {
    getBackgroundImageStyle(url) {
      return `backgroundImage: url(${this.domain}${url})`;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id ="app">
  <div 
    class="gallery-cell"
    v-for="item in items" 
    :style="getBackgroundImageStyle(item.url)">
    {{ item.text }}
  </div>
</div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related