当前位置:首页 > VUE

vue实现li高亮效果

2026-01-21 12:37:23VUE

Vue实现li高亮效果的方法

方法一:使用动态class绑定 通过v-bind:class或简写:class动态切换高亮样式,结合v-for渲染列表:

<template>
  <ul>
    <li 
      v-for="(item, index) in list" 
      :key="index"
      :class="{ 'highlight': activeIndex === index }"
      @click="activeIndex = index"
    >
      {{ item.text }}
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      list: [
        { text: 'Item 1' },
        { text: 'Item 2' },
        { text: 'Item 3' }
      ],
      activeIndex: -1
    }
  }
}
</script>

<style>
.highlight {
  background-color: yellow;
  font-weight: bold;
}
</style>

方法二:使用内联样式 通过:style直接绑定样式对象,适合需要动态计算样式的场景:

<li 
  v-for="(item, index) in items"
  :key="index"
  :style="{
    backgroundColor: activeId === item.id ? '#ffeb3b' : '',
    color: activeId === item.id ? '#000' : ''
  }"
  @click="activeId = item.id"
>
  {{ item.name }}
</li>

方法三:使用计算属性 当高亮逻辑较复杂时,可通过计算属性返回样式或class:

computed: {
  liClasses() {
    return this.items.map(item => ({
      'active-item': this.selectedItem === item.id,
      'disabled': item.disabled
    }))
  }
}

方法四:组件化封装 对于复用场景,可封装为可配置的组件:

<highlight-list 
  :items="dataList" 
  highlight-class="custom-highlight"
  @item-click="handleClick"
/>

注意事项

vue实现li高亮效果

  • 高亮状态应存储在组件data或Vuex中
  • 移动端建议添加:active伪类提升点击反馈
  • 性能优化:大数据列表使用v-virtual-scroll避免DOM过度渲染

标签: 效果vue
分享给朋友:

相关文章

vue实现波形

vue实现波形

实现波形效果的方法 在Vue中实现波形效果可以通过多种方式完成,常见的方法包括使用Canvas绘制、CSS动画或第三方库。以下是几种实现方案: 使用Canvas绘制波形 通过Canvas API动态…

vue实现链接

vue实现链接

Vue 实现链接的方法 在 Vue 中实现链接可以通过多种方式,包括使用 <router-link>、<a> 标签或编程式导航。以下是几种常见的方法: 使用 <rout…

vue实现api

vue实现api

Vue 实现 API 调用 在 Vue 中调用 API 通常涉及使用 axios 或 fetch 发送 HTTP 请求,并结合 Vue 的响应式特性管理数据。以下是常见的实现方式: 安装 axios…

vue 实现平面

vue 实现平面

Vue 实现平面的方法 在 Vue 中实现平面效果通常涉及 CSS 样式、UI 框架或自定义组件的使用。以下是几种常见方法: 使用 CSS 样式 通过 Vue 的样式绑定或 scoped CSS 为…

vue实现京东

vue实现京东

Vue 实现京东电商网站的关键步骤 项目搭建与基础配置 使用 Vue CLI 或 Vite 初始化项目,安装 Vue Router 管理路由,Vuex/Pinia 管理状态。配置基础 UI 框架如 E…

轮播vue实现

轮播vue实现

使用 Vue 实现轮播功能 基础轮播实现 安装依赖(如使用 Swiper): npm install swiper vue-awesome-swiper 组件代码示例: <template&…