You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js按钮点击切换实现方案咨询:点击后隐藏当前按钮显示另一个

Vue.js Solution: Toggle Buttons on Click

Got it, this is a straightforward task in Vue.js—we'll use a reactive state to control which button is visible. Below are solutions for both Vue 3 (with the modern <script setup> syntax) and Vue 2/Vue 3 Options API, so you can pick what fits your project.

Vue 3 (Composition API with <script setup>)

This is the most common approach for new Vue 3 projects. We'll use a reactive boolean ref to track which button should be shown:

<template>
  <!-- First button: visible when showFirstButton is true -->
  <button v-if="showFirstButton" @click="toggleButtons">
    Click me to switch
  </button>

  <!-- Second button: visible when showFirstButton is false -->
  <button v-else>
    I'm the second button!
  </button>
</template>

<script setup>
import { ref } from 'vue';

// Reactive state to control button visibility
const showFirstButton = ref(true);

// Function to toggle the state when the first button is clicked
const toggleButtons = () => {
  showFirstButton.value = false;
};
</script>

How it works:

  • showFirstButton is a reactive ref that starts as true, so the first button is visible initially.
  • When the first button is clicked, toggleButtons sets showFirstButton.value to false, which hides the first button and shows the second one immediately.
  • We use v-if/v-else here for direct conditional rendering—you could also use v-show if you prefer to keep the buttons in the DOM but toggle their display (both work for this use case).

Vue 2 / Vue 3 Options API

If you're working with Vue 2 or prefer the Options API syntax, here's the equivalent solution:

<template>
  <button v-if="showFirstButton" @click="toggleButtons">
    Click me to switch
  </button>
  <button v-else>
    I'm the second button!
  </button>
</template>

<script>
export default {
  data() {
    return {
      showFirstButton: true
    };
  },
  methods: {
    toggleButtons() {
      this.showFirstButton = false;
    }
  }
};
</script>

Key notes:

  • The logic is identical—we just use the Options API's data property to hold the reactive state instead of a ref.
  • The toggleButtons method updates the state when the first button is clicked, triggering the DOM update to swap the buttons.

If you ever need to toggle back later (e.g., click the second button to show the first again), you could adjust the method to flip the state instead of setting it to false: showFirstButton.value = !showFirstButton.value (for Composition API) or this.showFirstButton = !this.showFirstButton (for Options API).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:49:24