Vue.js - 如何动态切换图片的URL?

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

我正在开发一个网站,用户可以通过无线电 selection select 图片。 我想根据用户的 selection 动态更新图像 URL。我的方法是使用一个计算变量,该变量 returns 来自对象列表的 URL,具体取决于用户的 selection。

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

不幸的是,我收到一条错误消息 Critical dependency: the request of a dependency is an expression

浏览器控制台显示:[Vue warn]: Error in render: "Error: Cannot find module '../assets/background/bg_1.png'"

问题:动态切换图片URL的正确方法是什么?

感谢您的帮助!

这是一个工作示例:

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>

我删除了 require

源代码是 link/path,因此您不需要 requirerequire 将尝试采用路径并将其加载到模块中而不是 link/path。

希望这对您有所帮助。