[Vuejs]-Vue.js – How to switch the URL of an image dynamically?

3👍

Here is a working example:

var app = new Vue({
  el: '#app',
  data: () => ({
    currBackground: 0,
    backgrounds: [
      {
        name: "black",
        url: "https://dummyimage.com/600x400/000/fff"
      },
      {
        name: "blue",
        url: "https://dummyimage.com/600x400/00f/fff"
      },
      {
        name: "red",
        url: "https://dummyimage.com/600x400/f00/fff"
      }
    ]
  }),
  computed: {
      currBackgroundURL: function() {
          return this.backgrounds[this.currBackground].url
      }
  },
  methods: {
    nextImage() {
      this.currBackground += 1
      if (this.currBackground > 2) {
        this.currBackground = 0
      }
    }
  }
})
<html>
<head>
  <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
</head>
<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.18/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.js"></script>

  <div id="app">
      <v-btn @click="nextImage()">Change image</v-btn>
      <v-img
          :src="currBackgroundURL"
          class="my-3"
          contain
          width="397"
          height="560"
      ></v-img>
  </div>
</body>

I removed the require.

The src is a link/path so you don’t need require. require will try to take a path and load it into a module instead of a link/path.

Hopefully, this helps.

Leave a comment