当前位置:首页 > VUE

vue排他思想实现

2026-02-10 18:19:22VUE

Vue 排他思想实现

排他思想指的是在一组元素中,仅允许一个元素处于激活状态,其他元素自动取消激活。以下是几种常见的实现方法:

使用 v-for 和 v-model

通过 v-model 绑定一个变量,结合 v-for 动态生成元素,点击时更新绑定的变量。

vue排他思想实现

<template>
  <div>
    <button 
      v-for="item in items" 
      :key="item.id" 
      @click="selectedItem = item.id"
      :class="{ active: selectedItem === item.id }"
    >
      {{ item.name }}
    </button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: '选项1' },
        { id: 2, name: '选项2' },
        { id: 3, name: '选项3' }
      ],
      selectedItem: null
    }
  }
}
</script>

<style>
.active {
  background-color: #42b983;
  color: white;
}
</style>

使用计算属性

通过计算属性动态判断当前选中项,避免直接操作 DOM。

vue排他思想实现

<template>
  <div>
    <button 
      v-for="item in items" 
      :key="item.id" 
      @click="toggleActive(item.id)"
      :class="{ active: isActive(item.id) }"
    >
      {{ item.name }}
    </button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: '选项1' },
        { id: 2, name: '选项2' },
        { id: 3, name: '选项3' }
      ],
      activeItem: null
    }
  },
  methods: {
    toggleActive(id) {
      this.activeItem = id
    },
    isActive(id) {
      return this.activeItem === id
    }
  }
}
</script>

使用事件总线或 Vuex

对于跨组件排他操作,可以通过事件总线或 Vuex 管理全局状态。

// 使用事件总线
import Vue from 'vue'
const EventBus = new Vue()

// 组件A
EventBus.$emit('set-active', itemId)

// 组件B
EventBus.$on('set-active', (id) => {
  this.activeItem = id
})

动态样式绑定

通过 :class:style 动态切换样式,实现视觉排他效果。

<button 
  v-for="item in items" 
  :key="item.id" 
  @click="selectedItem = item.id"
  :style="{ 
    backgroundColor: selectedItem === item.id ? '#42b983' : '', 
    color: selectedItem === item.id ? 'white' : '' 
  }"
>
  {{ item.name }}
</button>

以上方法均能实现排他效果,选择取决于具体场景和项目复杂度。

标签: 思想vue
分享给朋友:

相关文章

vue实现裁剪头像

vue实现裁剪头像

Vue 实现头像裁剪功能 实现头像裁剪功能通常需要结合第三方库如 cropperjs 或 vue-cropper。以下是两种常见实现方式: 使用 vue-cropper 库 安装依赖: npm i…

vue实现mvc

vue实现mvc

Vue 实现 MVC 模式 Vue 本身是一个 MVVM(Model-View-ViewModel)框架,但可以通过结构调整实现 MVC(Model-View-Controller)模式。以下是具体实…

vue实现选区

vue实现选区

Vue 实现选区的基本方法 在Vue中实现选区功能通常涉及DOM操作和事件处理。以下是几种常见的方法: 使用原生JavaScript的Selection API 通过window.getSelec…

vue树形实现

vue树形实现

Vue 树形组件实现方法 使用递归组件实现树形结构 递归组件是 Vue 中实现树形结构的常见方法。通过组件调用自身的方式,可以轻松构建多层嵌套的树形结构。 <template> &l…

vue实现tag

vue实现tag

Vue 实现标签(Tag)功能 在 Vue 中实现标签(Tag)功能可以通过多种方式完成,以下是一些常见的方法和实现步骤: 使用动态组件和 v-for 通过 v-for 指令动态渲染标签列表,结合样…

vue实现github

vue实现github

Vue 实现 GitHub 相关功能 创建 GitHub API 请求 在 Vue 项目中,可以使用 axios 或 fetch 与 GitHub API 进行交互。需要在 GitHub 上创建个人访…