[Vuejs]-Change a toggle in VueJS to two buttons to show and hide elements

1👍

Maybe just create a seperate property for each part of your app? (If you have a lot of components, it might make sense to combine those into an array)

I imagined something like this:

<template>
  <button @click="showPart1 = !showPart1">Toggle Part 1</button>
  <button @click="showPart2 = !showPart2">Toggle Part 2</button>

  <span v-if="showPart1">
    <h1>Part 1</h1>
  </span>
  <span v-if="showPart2">
    <h1>Part 2</h1>
  </span>
</template>

<script>
export default {
  name: "App",
  data: function () {
    return {
      showPart1: true,
      showPart2: false,
    };
  },
};
</script>

0👍

When you will want to add some logic to those toggles is better to do like this and add some additional logic in methods. In the button is trigger only but logic is placed in methods. It’s is more readable.

<template>
  <button @click="showPart1">Toggle Part 1</button>
  <button @click="showPart2">Toggle Part 2</button>

  <span v-if="showPart1">
    <h1>Part 1</h1>
  </span>
  <span v-if="showPart2">
    <h1>Part 2</h1>
  </span>
</template>

export default {
    setup() {
        const showPart1 = false;
        const showPart2 = false;


        return {
            showPart1,
            showPart2,
        }
    },
    methods: {
    showPart1() {
    //additional logic for showPart1
    console.log(showPart1);
    },
    showPart2() {
    //additional logic for showPart1
    console.log(showPart1);
    },
    data() {
        return {
            showPart1: false,
            showPart2: false,
        }
    }
}
</script>

Leave a comment