Images Gradient in Vue2

Realize image gradient effect in Vue2.

Template

  1. Use as a wrapper for setting the gradient animations.
  2. Use v-for directive to traverse the list of images.
  3. Use v-show directive to show the current image and hide the others images.
  4. Use :style directive to bind a background-image style for each
    and display each images as a background-image of the
    .
1
2
3
4
5
6
7
8
9
10
<transition-group tag="ul" name="img">
<li
class="image-container"
v-for="(img, index) in imgArr"
:key="index"
v-show="index === currIndex"
>
<div class="image" :style="{'background-image': 'url(' + i + ')'}"></div>
</li>
</transition-group>

Data

  1. currIndex, represent the index of current image.
  2. imgArr, which saved the relative link of all images.
1
2
3
4
5
6
7
currIndex: 0,
imgArr: [
require('../../assets/background/A01.webp'),
require('../../assets/background/A02.webp'),
require('../../assets/background/A03.webp'),
require('../../assets/background/A04.webp'),
]
  • Notice: Remember to use require() to parse the relative link, otherwise it can’t get the images

Methods

  • autoPlay, a method to update the currIndex in each n seconds.
  • Call the method when the component is mounted.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    methods: {
    autoPlay(){
    setInterval(() => {
    this.currIndex = (this.currIndex < this.imgArr.length - 1) ? this.currIndex + 1 : 0
    }, 4000);
    }
    },
    mounted(){
    this.autoPlay()
    },

Styles

  • Apply the animation: set the opacity, transition and z-index for the entering and leaving element.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    .img-enter-active {
    transition: opacity 3s ease;
    }
    .img-leave-active {
    transition: 3s;
    z-index: -100;
    }
    .img-enter{
    opacity: 0;
    }
    .img-enter-to{
    opacity: 1;
    }