Search code examples
vue.jscomponentsvuejs3show-hide

Vue.js showing and hiding component on click


I'm trying to show/hide an element on click, I've tried many things but I don't think I'm setting up my methods properly.

Here's my Main.js

import './assets/main.css'
import home from '../src/pages/home.vue'
import boards from '../src/pages/boards.vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import { createApp } from 'vue'
import App from './App.vue'
import masonry from 'vue-next-masonry';

const Home = { template: home}
const Boards = { template: boards}

const routes = [
    { path: '/', name: "home", component: home},
    { path: '/boards', name: "boards", component: boards},
]

const router = createRouter({
    history: createWebHashHistory(),
    routes,

})


createApp(App).use(router).use(masonry).mount('#app')

And this is a snippet of the code where I'm trying to create that functionality:



    methods: {
        showComponent() {
                this.$refs.card.show();
            
        },

        hideComponent() {
            this.$refs.card.hide();
        }
    },

    
}
</script>

<template>
    <div class="m-10">
        <h1 class="text-gray-200 font-sans md:font-mono text-center text-4xl mb-5">Welcome to your feed.</h1>
            <masonry :cols="4" :gutter="10">
                <div v-for="(image, index) in images" :key="image">
                    <button @click="showComponent">
                        <img class="transition ease-in-out delay-150 hover:opacity-10 h-auto max-w-full rounded-lg mt-2" :src="image.src">
                    </button>
                </div>
            </masonry>
        </div>
    <div v-if="showComponent" id="card" class="box-border h-128 w-128 p-4 border-4 bg-gray-300">
        <h1>Test</h1>
        <button @click="hideComponent">
            <h1>Close</h1>
        </button>
    </div>
</template>

<style>

</style>

I've looked at a few questions here on stackoverflow regarding my issue but I can't seem to get any of it to work and I think I'm missing something


Solution

  • You can initialize a ref variable and toggle its state

    <script setup>
    import { ref } from "vue"
    
    const showComponent = ref(false) // hiding it by default
    </script>
    

    Then with your show component button

    <button @click="showComponent = true">Show Component</button>
    

    Hide component button

    <button @click="showComponent = false">Show Component</button>
    

    Component to toggle visibility

    <div v-if="showComponent">Card</div>
    

    If you want to create a single button to toggle visibility

    <button @click="showComponent = !showComponent">Toggle Component</button>
    

    With Vue 2 (Options API)

    <script>
    export default {
      data() {
        return {
          showComponent: false
        }
      }
    }
    </script>