当电流处于活动状态时,在@click on button 上添加活动 class - Composition API

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

7 天前,我开始使用 Vue.js 我有这个简单的应用程序,我在其中列出工作并有 4 个过滤器,带有 handleClick 函数来过滤地点、薪水、公司和职位。

现在我想了解如何使用 Vue 中的组合 API 添加活动 class?

我知道如何在 React 中完美地完成同样的操作,但想知道如何使用 Vue 完成此操作。

代码:

<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>

您是否尝试绑定 class:

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

您还可以将 class 绑定到变量或计算的 属性 以防您需要更多选项。例如你正在使用 BEM 或类似的方法来 CSS class 命名,然后你的代码可能是这样的

<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';
  })
 }
},