[Vuejs]-Element in VueJS template reference self

1๐Ÿ‘

I would assume that the ?? is intended to be something uniquely identifying to the active element.

<template>
  <div v-on:click="show('Slide1')" v-bind:class="{ 'active': activeSlide === 'Slide1' }"></div>

  <div v-on:click="show('Slide2')" v-bind:class="{ 'active': activeSlide === 'Slide2' }"></div>
</template>

<script>
  export default {
    data() {
        return {
            activeSlide: null
        }
    }
    methods: {
       show: function(value) {
           this.activeSlide = value;
       }
    } 
}
</script>

So basically when you click the slide it will change the activeSlide property to the value passed into the v-on:click method.

There are more dynamic ways of doing this such as if you were to loop through a series of elements you could then compare the active index to the index of the element instead of explicitly saying Slide1 or Slide2.

Here is a dynamic example

<template>
  <div v-for="slide in slides" :key="slide.id" v-on:click="show(slide.id)" v-bind:class="{ 'active': activeSlide === slide.id }"></div>
</template>

<script>
  export default {
    data() {
        return {
            activeSlide: null
        }
    }
    methods: {
       show: function(value) {
           this.activeSlide = value;
       }
    } 
}
</script>

so you can use any available data in the iteration to compare, just pass in slide.whatever to the method and set the class to equal the same thing.

๐Ÿ‘คTJ Weems

Leave a comment