我试图在单击时显示/隐藏一个元素,我已经尝试了很多方法,但我认为我没有正确设置我的方法。
这是我的 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')
这是我尝试创建该功能的代码片段:
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>
我在 stackoverflow 上查看了一些关于我的问题的问题,但我似乎无法让其中任何一个发挥作用,我认为我错过了一些东西
您可以初始化
ref
变量并切换其状态
<script setup>
import { ref } from "vue"
const showComponent = ref(false) // hiding it by default
</script>
然后使用显示组件按钮
<button @click="showComponent = true">Show Component</button>
隐藏组件按钮
<button @click="showComponent = false">Show Component</button>
切换可见性的组件
<div v-if="showComponent">Card</div>
如果您想创建一个按钮来切换可见性
<button @click="showComponent = !showComponent">Toggle Component</button>