Lucien Chardon
Lucien Chardon

Reputation: 461

Vue.js - How to switch the URL of an image dynamically?

I am working on a site where the user can select an image via radio selection. I would like to dynamically update the image URL depending on selection of the user. My approach is to use a computed variable which returns the URL from a list of objects depending on the selection of the user.

<template>
    <v-img
        :src="require(currBackgroundURL)"
        class="my-3"
        contain
        width="397"
        height="560"
    ></v-img>
</template>

<script>
    // data() ...
    currBackground: 0,
    backgrounds: [
      {
        name: "Flowers",
        url: "../assets/background/bg_1.png"
      },
       // ...
  computed: {
      currBackgroundURL: function() {
          return this.backgrounds[this.currBackground].url
      }
  }
</script>

Unfortunately, i get an error which says Critical dependency: the request of a dependency is an expression.

And the browser console says: [Vue warn]: Error in render: "Error: Cannot find module '../assets/background/bg_1.png'"

Question: What is the right way to switch the URL of the image dynamically?

Thanks for your help!

Upvotes: 0

Views: 4822

Answers (1)

anbcodes
anbcodes

Reputation: 849

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.

Upvotes: 3

Related Questions