Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs image url link

Tags:

vue.js

Hi I am really new to vuejs. I try to import a picture then call this picture in the methods.

import image from '@/assets/svg/xxx.svg'

then in the data

data () {
        return {
            image: image
        }
    },

and try to use it

li.style.backgroundImage = "url('this.image')";

But the image is not showing, and image link show as following

http://127.0.0.1:8080/order/detail/29/this.image

I really not sure where i get wrong...Please help...

like image 351
Xiaozhou Song Avatar asked Oct 15 '25 03:10

Xiaozhou Song


2 Answers

A another way to doing it using computed property on style attribute :

computed : {
    liStyle(){
        return "background-image : url('" + require('@/assets/svg/xxx.svg') + "')";
    }
}

Template :

<li :style="liStyle"></li>
like image 85
Ekushisu Avatar answered Oct 17 '25 14:10

Ekushisu


I think the better (and scalable) solution it's to have a class which sets the styles you want, and add it to the elements, if it have to be dinamically, just add it with :class on some condition.

note: i used an external image path, but it's the same with your local path. And use require() to import images and html

new Vue({
  el: '#example'
})
.li-with-bg-image {
  background-image: url('http://via.placeholder.com/350x150')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="example">
  <ul>
    <li :class="{'li-with-bg-image': true}"></li>
    <li></li>
    <li class="li-with-bg-image"></li>
  </ul>
</div>

Another options

Using inline styles (using v-bind:style)

new Vue({
  el: '#example'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="example">
  <ul>
    <li :style="`background-image: url('http://via.placeholder.com/350x150')`"></li>
  </ul>
</div>

Using data section or a computed property binded to style

new Vue({
  el: '#example',
  data: {
    myStyles: `background-image: url('http://via.placeholder.com/350x150')`
  },
  computed: {
    anotherStyles () { 
      return `background-image: url('http://via.placeholder.com/300x150')`
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="example">
  <ul>
    <li :style="myStyles"></li>
    <li></li>
    <li :style="anotherStyles"></li>
  </ul>
</div>

Resources:

Class and style bindings Docs

like image 28
DobleL Avatar answered Oct 17 '25 14:10

DobleL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!