当current为活动时,在@click on按钮上添加活动类-Composition API



7天前,我开始使用Vue.js。我有一个简单的应用程序,可以列出工作,并有4个过滤器,带有handleClick功能,可以过滤位置、工资、公司和职位。

现在我正在尝试理解如何使用Vue中的Composition API添加活动类?

我知道如何在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>

您是否尝试绑定类:

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

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

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

最新更新