Home > Blockchain >  Show/hide menu in Vue 3
Show/hide menu in Vue 3

Time:07-19

I want to show and hide the menu when i click the menu-button. Don't really know how to get forward with this? I want to write it with Vue 3.

const openMenu = () => {
    showMenuContent: {
        type: Boolean
        required: true,
        default: false,
    }
}
<a  @click="openMenu()">Menu</a>

        <div v-if="showMenuContent(true)">Menu-div</div>

CodePudding user response:

use a reactive variable to toggle the menu on/off

example using script setup

import { ref } from 'vue';
const isOpen = ref(false)

template

<button @click="isOpen = !isOpen">Menu</button>

<div v-if="isOpen">Menu-div</div>

CodePudding user response:

The syntax you're using is typically used for props, inside defineProps().


A. If menu state is managed in current component

Use a reactive variable:

const isMenuOpen = ref(false);
const toggleMenu = () => isMenuOpen.value = !isMenuOpen.value;

See it working:

const { createApp, ref } = Vue

createApp({
  setup() {
    const isMenuOpen = ref(false);
    const toggleMenu = () => { 
      isMenuOpen.value = !isMenuOpen.value;
    }
    return { isMenuOpen, toggleMenu }
  }
}).mount('#app')
<script src="https://unpkg.com/vue/dist/vue.global.prod.js"></script>
<div id="app">
  <a href="#" @click.prevent="toggleMenu">Menu</a>
  <div v-if="isMenuOpen">Menu-div</div>
</div>

Note: If you write the toggleMenu function inline (e.g: in the template), the ref is unwrapped, so you don't need .value:

  <a href="#" @click.prevent="isMenuOpen = !isMenuOpen">Menu</a>

B. If menu state is managed in parent component

Use v-model:

Parent:

<script setup>
  const showMenuContent = ref(false)
</script>
<template>
  <your-menu v-model:show-menu-content="showMenuContent" />
</template>

Child (e.g: YourMenu.vue):

<script setup>
  const props = defineProps({
    showMenuContent: {
      type: Boolean,
      default: false
    }
  })
  const emit = defineEmits('update:showMenuContent')
  const toggleMenu = () =>
    emit('update:showMenuContent', !props.showMenuContent)
</script>
<template>
  <a href="#" @click.prevent="toggleMenu">Menu</a>
  <div v-if="showMenuContent">Menu-div</div>
</template>

See it working:

const { createApp, ref, defineComponent } = Vue

const MenuComponent = defineComponent({
  template: `
<a href="#" @click.prevent="$emit('update:showMenuContent', !showMenuContent)">Menu</a>
<div v-if="showMenuContent">Menu-div</div>
`,
  props: {
    showMenuContent: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:showMenuContent']
})

createApp({
  components: {
    MenuComponent
  },
  setup: () => ({
    showMenuContent: ref(false)
  })
}).mount('#app')
<script src="https://unpkg.com/vue/dist/vue.global.prod.js"></script>
<div id="app">
  <menu-component v-model:show-menu-content="showMenuContent" />
</div>

  • Related