Vue.js按钮点击切换实现方案咨询:点击后隐藏当前按钮显示另一个
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:
showFirstButtonis a reactive ref that starts astrue, so the first button is visible initially.- When the first button is clicked,
toggleButtonssetsshowFirstButton.valuetofalse, which hides the first button and shows the second one immediately. - We use
v-if/v-elsehere for direct conditional rendering—you could also usev-showif 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
dataproperty to hold the reactive state instead of a ref. - The
toggleButtonsmethod 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

