Skip to main content

Imagine you want to create a list with Vuejs.

To do this you will create a component (eg: "fueltypes") that will have a <li> element as template and that  you will include like this :

            <ul class="tabs">
                <fueltypes
                        v-for="fueltype in fueltypes"
                        v-bind:fueltype="fueltype"
                        :key="fueltype.value">
                </fueltypes>
            </ul>

Imagine now that you want apply a class on one of these rendered element when clicking on it. First, we would add an "on-click" event on each rendered element and that event would change a property of the component. A problem would be always present, if you click on the element, others elements that were already clicked would not change. To avoid this, you should add an event (eg: change-link-active) on the component and this event would change the property for each element :

           <ul class="tabs">
                <fueltypes
                        v-for="fueltype in fueltypes"
                        v-bind:fueltype="fueltype"
                        :link_active="link_active"
                        @change-link-active="link_active = $event"
                        :key="fueltype.value">
                </fueltypes>
            </ul>

In the method (changeActiveClass) called on the event "on-click" in our component it will be necessary to call $emit with a unique value (here fueltype.id) which will be passed in parameter to trigger our event "change-link-active". This unique value will be used for the condition to display the class or not on the element:

 <template>
  <li class="tab">
    <div class="col-md-12">
      <a v-bind:id="'fuel_type_'+fueltype.class"
         v-bind:href="'#'+fueltype.class"
         @click="changeActiveClass(fueltype.id)"
         v-bind:class="[fueltype.class, {active:link_active == fueltype.id} ]">
        {{ fueltype.label }}
      </a>
    </div>
  </li>
</template>
<script>
    export default {
        props: {
            fueltype: {
                type: Object,
                required: true
            },
            link_active: {
                type: Number,
                required: false
            },
        },
        methods: {
            changeActiveClass (id) {
                this.$emit('change-link-active', id);
            }
        },
    }
</script>

Étiquettes
Let's discuss your project

Contact us

  •  + 32 (0) 10 49 51 00
  •  info@expert-it.com