首页 > 解决方案 > Vue.js 通过单击更改图像 src

问题描述

我需要有关切换图像的帮助。当我单击图像时,我希望它从源列表中更新,例如每次单击时从 4 个源中更新。因此,每次单击都会使用列表中的下一个源更新图像。我在 Vue 方面不是最好的,但我正在学习。我已经尝试过这样做,但还没有弄清楚。如果有人能告诉我如何在 Vue 代码中执行此操作,那将非常有帮助。

标签: javascriptimagevue.jsonclick

解决方案


这是如何在 vue 中解决图像切换的示例。

var app = new Vue({
  el: "#app",
  data() {
    return {
      index: 0,
      image: null,
      images: [{
          id: 1,
          src: "https://r1.ilikewallpaper.net/ipad-wallpapers/download/26516/Natural-Grove-Green-Trees-Path-ipad-wallpaper-ilikewallpaper_com.jpg",
          alt: "Natural Grove Green Trees Path"
        },
        {
          id: 2,
          src: "https://st2.depositphotos.com/1000438/6182/i/950/depositphotos_61826015-stockafbeelding-cascades-in-nationaal-park-plitvice.jpg",
          alt: "stockafbeelding cascades in nationaal park plitvice"
        },
        {
          id: 3,
          src: "https://orig00.deviantart.net/6787/f/2016/104/5/6/aria_maleki___natural_view_of_waterfall_by_aria_maleki-d9yytu8.jpg",
          alt: "natural view of waterfall"
        }
      ]
    }
  },
  mounted() {
    this.switchImage();
  },
  methods: {
    switchImage() {
      this.image = this.images[this.index];
      this.index = (this.index + 1) % this.images.length;
    }
  }
});
.image {
  width: 100px;
  height: 100px;
  margin: 2px;
  cursor: pointer;
  transition: filter 0.3s ease-in;
}

.image:hover {
  filter: brightness(1.2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <img v-if="image" :key="image.id" @click="switchImage" class="image" :src="image.src" alt="image.alt">
</div>


推荐阅读