当前位置:首页 > 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实现放大缩小功能的方法 在Vue中实现元素的放大缩小功能,可以通过CSS变换、第三方库或直接操作DOM样式来实现。以下是几种常见的方法: 使用CSS transform属性 通过绑定Vue的d…

vue 实现弹幕

vue 实现弹幕

vue 实现弹幕的方法 使用 CSS 动画和动态渲染 在 Vue 中实现弹幕效果,可以通过动态渲染弹幕元素并结合 CSS 动画实现。以下是具体步骤: 数据准备 创建一个数组存储弹幕数据,每条弹幕包…

vue实现Siri

vue实现Siri

Vue 实现 Siri 风格语音交互 实现类似 Siri 的语音交互功能需要结合语音识别、语音合成和前端交互逻辑。Vue 作为前端框架,可以很好地管理这些功能的交互状态。 语音识别集成 使用 Web…

vue首页实现

vue首页实现

实现Vue首页的基本步骤 创建一个Vue首页通常涉及项目初始化、页面结构设计、路由配置和组件开发。以下是具体实现方法: 初始化Vue项目 使用Vue CLI或Vite快速搭建项目结构: npm i…

vue实现录像

vue实现录像

Vue 实现录像功能 在 Vue 中实现录像功能通常需要借助浏览器的 MediaDevices API 和 MediaRecorder API。以下是实现步骤: 获取用户摄像头和麦克风权限 使用 n…

vue拖动实现

vue拖动实现

实现 Vue 拖动功能的方法 使用 HTML5 拖放 API 在 Vue 中可以利用 HTML5 的原生拖放 API 实现拖动功能。通过 draggable 属性标记可拖动元素,结合 @dragsta…