[Vuejs]-How to manipulate/hide slot elements in child components in Vue Js

0👍

Vue SFC Playground

What are you trying to do is to pass a component attributes to a specific NON-root element.

For that you should turn off automatic inheritance of attributes to a root of a component with inheritAttrs: false and assign the attributes manually to your element of choice with the $attrs variable in the template;

About disabling attribute inheritance in the Vue docs:
https://vuejs.org/guide/components/attrs.html#disabling-attribute-inheritance

The slot is not needed here (besides passing a custom button label) and you try to insert a button into a button hoping that would merge into 1 button with the expected behavior which is definitely won’t work.

So the your component Answer.vue:

<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 name="checkAnswer">Check answer</slot>
      </button>
    </div>
</template>

App.vue

<script setup>

  import {ref} from 'vue';
    import Answer from './Answer.vue';

  const isAnswerChecked = ref(false);

</script>

<template>
  <answer 
    @click="isAnswerChecked = true" 
    :disabled="isAnswerChecked"
          :class="{
            ' text-gray-300 border-gray-300  ': isAnswerChecked,
          }">
    <template #checkAnswer>
      Check answer carefully
    </template>
  </answer>
</template>

Leave a comment