Add active class on @click on button when current is active - Composition API

Viewed 309

7 days ago I've started working with Vue.js I have this simple App where I am listing jobs and having 4 filters with a handleClick function to filter on location, salary, company, and title.

Now I am trying to understand how can I add an active class using the Composition API in Vue?

I know how to do this same in React perfectly fine, but wondering how this is done with Vue.

Code:

<template>
  <div class="app">
    <header>
      <div class="order">
        <button @click="orderByTerm('title')">Order by title</button>
        <button @click="orderByTerm('salary')">Order by salary</button>
        <button @click="orderByTerm('location')">Order by location</button>
        <button @click="orderByTerm('company')">Order by company</button>
      </div>
    </header>
    <JobList :jobs="jobs" :order="order" />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";

import JobList from "./components/JobList.vue";

import Job from "./types/Job";
import OrderTerm from "./types/OrderTerm";

import AllJobs from "./data/jobs";

export default defineComponent({
  name: "App",
  components: { JobList },
  setup() {
    const jobs = ref<Job[]>(AllJobs);

    const order = ref<OrderTerm>("title");

    const orderByTerm = (term: OrderTerm) => {
      order.value = term;
    };

    return { jobs, orderByTerm, order };
  },
});
</script>
2 Answers

Did you try to bind class:

<button @click="orderByTerm('company')" :class="order === 'company' ? 'active' : ''">
...

You can also bind class to a variable or a computed property in case you need more options. For instance you are using BEM or similar approach to CSS class naming, and then you code could be like this

<aside class="admin-menu__aside" :class="menu_expanded" ref="menu_aside">

data(){
 return {
  menu_expanded: null
 }
}

methods: {
expand_menu(){
  const media = window.matchMedia('(min-width: 1024px)');
  if(!media.matches) return; 
  this.$refs.menu_aside.addEventListener('mouseenter', () => {
    this.menu_expanded = 'admin-menu__aside-full';
  })
  this.$refs.menu_aside.addEventListener('mouseleave', () => {
    this.menu_expanded = 'admin-menu__aside-small';
  })
 }
},
Related