So I have a button that I want to use multiple times, as a component with a slot
<div name="checkAnswer" class="w-[70%] mx-[15%] flex items-center justify-center" > <button class="p-3 rounded-3xl shadow-md font-bold m-4 px-10 border-2 border-grey-800 hover:border-black hover:transition-all hover:duration-500" > <slot name="checkAnswer"></slot> </button> </div>
But when I wanted to use it, I couldn't use @click="method" on the slot button, so I used a nested button (I had a slot button and then another button just to Use @click="method"):
<template #checkAnswer> <button @click="checkAnswer" :disabled="isAnswerChecked" :class="{ ' text-gray-300 border-gray-300 ': isAnswerChecked, }" > Check answer </button> </template>
This works, but it's invalid HTML. How can I solve it?
P粉9208354232023-09-16 09:19:51
You need to use v-bind="$attrs"
to bind the properties of the button component to <button>
in the template, and disable the For default attribute inheritance, use inheritAttrs:false
.
Also, you don't need to use named slots here, just use the default ones:
<script> export default { inheritAttrs: false, // 这是禁用属性继承的设置 }; </script> <template> <div name="checkAnswer" class="w-[70%] mx-[15%] flex items-center justify-center" > <button v-bind="$attrs" class="p-3 rounded-3xl shadow-md font-bold m-4 px-10 border-2 border-grey-800 hover:border-black hover:transition-all hover:duration-500" > <slot></slot> </button> </div> </template>
Parent component:
<script setup> import MyButton from './MyButton.vue'; import {ref} from 'vue'; const isAnswerChecked = ref(false); const checkAnswer = () => { alert('check answer!'); isAnswerChecked.value = true; }; </script> <template> <MyButton @click="checkAnswer" :disabled="isAnswerChecked" :class="{ ' text-gray-300 border-gray-300 ': isAnswerChecked, }" > Check answer </MyButton> </template>