You need to enable JavaScript to run this app. Vue组件不使用vue-router时如何为选中锚标签动态添加active类
优惠活动
大模型
产品
解决方案
定价
更多

Vue组件不使用vue-router时如何为选中锚标签动态添加active类

开发场景与诉求
  • 正在开发一个Vue导航组件,不打算引入vue-router
  • 要实现的核心效果很简单:点击任意导航链接时,动态给被点击的锚标签加上active类
  • 目前遇到的问题:之前浏览过平台上很多同类问题的解答,但现有方案都和自己的实际需求对不上,没法直接用

已完成的组件代码

<template>
  <nav>
    <ul>
      <li v-for="(item, $index) in items" :key="$index" >
        <a :href="item.link">{{ item.name }}</a>     // 这里要怎么动态加active类?
      </li>
    </ul>
  </nav>
</template>

<script>
export default {
  name: "Navbar",
  props: {
    items: {
      type: Array,
      default: null,
    },
  },
}
</script>

<style>
 ul li .active {
   background-color: red;
   cursor: pointer;
 }
</style>

实际使用的导航列表数据

const items = [
  {
    name: "Home",
    link: "#home",
  },
  { 
    name: "About", 
    link: "#about" 
  },
  {
    name: "Contacts",
    link: "#contact",
  },
];

内容的提问来源于stack exchange,提问作者deadbeforesunlight

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.12 01:54:07