javascript - vue js 中的自定义图像 slider

标签 javascript vue.js

尝试构建一个简单的自定义图像幻灯片,除了一件事之外,大部分都让它工作。当 :src 数据更改时,我想添加像 opacity:0 ~ 1 这样的过渡,但无法实现该部分。这是幻灯片。

模板

<img class="slide-image" :src="getImgUrl(images[0])">

脚本

data(){
    return {
        images: [
            "/images/home/home-slide1.png",
            "/images/home/home-slide2.png",
            "/images/home/home-slide3.png",
            "/images/home/home-slide4.png",
            "/images/home/home-slide5.png",
        ]
    };
},
watch: {    
    getImgUrl(){

    }
},
mounted(){
    window.setInterval(()=>{
        this.slide();
    }, 5000);
},
methods: {
    getImgUrl(im) {
        return require('../assets' + im)
    },
    slide(){
        let first = this.images.shift();
        this.images = this.images.concat(first);
    },
},

:src 每 5 秒更改一次时添加过渡的最佳且简单的方法是什么,如果有人可以指导这一点,我们将不胜感激。

最佳答案

<script>
export default {
  name: "Slider",
  data() {
    return {
      images: [
        "/images/home/home-slide1.png",
        "/images/home/home-slide2.png",
        "/images/home/home-slide3.png",
        "/images/home/home-slide4.png",
        "/images/home/home-slide5.png",
      ],
      timer: null,
      currentIndex: 0
    };
  },

  mounted: function() {
    this.startSlide();
  },

  methods: {
    startSlide: function() {
      this.timer = setInterval(this.next, 5000);
    },

    next: function() {
      this.currentIndex += 1;
    },
    prev: function() {
      this.currentIndex -= 1;
    }
  },

  computed: {
    currentImg: function() {
      return this.images[Math.abs(this.currentIndex) % this.images.length];
    }
  }
};
</script>

让我们看看我们在这里做了什么:

  • 我们获得了一组图像网址。
  • timer 设置为 null 并将 currentIndex 设置为 0 以显示第一张图像。
  • 创建了 startSlide 函数,用于每 4 秒滑动一次图像。
  • 创建了 nextprev 函数,用于滑动到上一张或下一张图像。根据最后一个 currentImg 函数,它会根据索引检测当时必须显示哪个图像。

HTML:

<template>
  <div>
    <transition-group name="fade" tag="div">
      <div v-for="i in [currentIndex]" :key="i">
        <img :src="currentImg" />
      </div>
    </transition-group>
    <a class="prev" @click="prev" href="#">&#10094; Previous</a>
    <a class="next" @click="next" href="#">&#10095; Next</a>
  </div>
</template>

这里我们利用Vue.js自带的内置transtion-group组件,然后迭代图像并添加我们之前创建的函数。

更多详细信息请参见:https://alligator.io/vuejs/create-image-slider/

关于javascript - vue js 中的自定义图像 slider ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61005346/

相关文章:

javascript - 选择除 $(this) 之外的所有类节点

vue.js - __dirname未定义导入 Electron Remote

html - 表格中的背景颜色不显示空单元格

vue.js - VeeValidate v3 : How to handle backend validation messages?

javascript - jquery 设置 tabindex 和游标

javascript - PHP 图片库与延迟加载

JavaScript 函数被忽略

javascript - Vue : Access Vue instance from function outside instance scope

vue.js - 将事件传递到组件 VueJS 的元素上

javascript - 使用 Jquery 从对象属性填充单选按钮