Tips for controlling or concealing slot elements within child components in Vue Js

I'm working with a named 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>

Here's how I use the named slot in my component:

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

I need to use the button tag for @click functionality, as it can't be applied directly to the template element.

However, I'm facing an issue. When the "Check answer" button is clicked, correct answers are displayed but I want to hide the button afterwards. The problem is that I can't seem to figure out how to hide the entire button - using v-show on the template element only hides the text within the button, leaving me with an empty button.

I've tried placing div elements inside and outside the template, but so far I haven't found a way to hide the button completely, not just its text.

Answer №1

Vue Component Playground

To achieve passing component attributes to a specific non-root element, it is necessary to disable automatic attribute inheritance to the root component by using inheritAttrs: false and manually assign the attributes to the desired element using the $attrs variable in the template;

For more information on disabling attribute inheritance in Vue, refer to the following link in the Vue documentation: https://vuejs.org/guide/components/attrs.html#disabling-attribute-inheritance

The use of slots is not required in this scenario unless you are passing a custom button label. Attempting to insert a button into another button in hopes of merging them into one will not result in the expected behavior.

The structure of your Answer.vue component:

<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 content:

<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting the non-functioning addEventListener in JavaScript

I am facing an issue where a function that should be triggered by a click event is not working and the console.log message does not appear <script src="e-com.js" async></script> This is how I included the javascript file in the head ...

Execute the function when the form is submitted and show the total of the two values

I am currently working on a straightforward custom module for Drupal 7. This module takes two numeric values and upon submission, displays the sum of these values on the same page. While I have the form set up, it is not yet complete. I am facing some dif ...

Dynamic Font Formatting in Rails Table Based on Conditions

I need to customize the font color of dynamic values based on the state_id. If incident.state_id = 1, the font should be red; if incident.state_id = 2, it should be yellow; and if incident.state_id = 3, it should be green. incident.state_id = 1 : state.na ...

Transforming the data retrieved from the API into a well-organized object in Vue.js

Currently, I am utilizing the vue-meta library to incorporate meta tags into my Vue project. What I'm attempting to do now is populate my meta tags using the API response data. Here's an example output from the API when I log 'response.data. ...

How can I transfer the total and counter values to a different PHP page and store them in a text box before saving them to the database?

I need to transfer the total and counter values to another PHP page using a text box and then save them to a database. { var price =10; //price $(document).ready(function() { var $cart = $('#selected-seats'), //Sitting Are ...

When using Selenium WebDriver in Java, we noticed that despite initially failing with JavascriptExecutor, the element click method with WebElement performed successfully

Within the code snippet below, it is evident that using the WebElement.click() method successfully triggers an element, while the JavascriptExecutor.executeScript method encounters issues (although it works in most cases). WebElement e = driver.findElemen ...

The environmental variables stored in the .env file are showing up as undefined in Next.js 13

I am having trouble accessing the environment variables stored in my .env.local file within the utils folder located in the root directory. When I try to console log them, they show as undefined. console.log({ clientId: process.env.GOOGLE_ID, clien ...

Ways to retrieve Payload following the Request url access

Currently utilizing Selenium with Python to conduct website testing, I successfully accessed the Request link and now aim to access the Payload. Below is an image displaying the process: view image description here driver = webdriver.Chrome(options=option) ...

Getting data from an API with authorization in Next.js using axios - a step-by-step guide

click here to view the image user = Cookies.get("user") I'm having trouble accessing this pathway. I stored user data, including the token, using cookies. Please assist me with this issue. ...

FullCalendar is encountering loading issues when trying to fetch data from JSON, with the

I am currently utilizing FullCalendar to create a schedule for theater rehearsals. After considering my options, I concluded that JSON would be the most efficient way to retrieve events from my MySQL database. In the JavaScript code for the calendar page, ...

Assign the value of "td" to the variable "val"

I am trying to set the value of my td element from my JavaScript JSON, but for some reason it doesn't seem to be working when I inspect the element. The HTML is functioning fine, it's just the value that isn't updating. I've tried chang ...

In Typescript, we can streamline this code by assigning a default value of `true` to `this.active` if `data.active

I am curious if there is a better way to write the statement mentioned in the title. Could it be improved with this.active = data.active || true? ...

Blank page shown when routing with Angular in Rails

Hey there, I'm currently attempting to integrate Angular into my Rails application and unfortunately I'm encountering a problem where the HTML page shows up blank. Here's the code I have so far: app/views/index.html.erb <body> ...

JavaScript Delayed Redirection

I'm attempting to launch opera from the command line and have it redirect to a page after 30 seconds. Here's what I currently have: C:\Programme\Opera\opera.exe -newpage javascript:function%20func1(){window.location.href='htt ...

Error with JavaScript callback functions

After creating a POST route, I encountered unexpected behavior in the code below. The message variable does not display the expected output. app.post("/", function (req, res, error) { var message = ""; tableSvc.createTable("tableName", function (error ...

Step by step guide on loading a dynamic Vue.js component from a different component

Currently, I am utilizing Laravel and VueJS2 to load components dynamically using the current view variable. After successfully loading a component this way, I now have a requirement to replace this loaded component with another one. Can someone guide me ...

Toggling the form's value to true upon displaying the popup

I have developed an HTML page that handles the creation of new users on my website. Once a user is successfully created, I want to display a pop-up message confirming their creation. Although everything works fine, I had to add the attribute "onsubmit= re ...

I am experiencing an issue where tapping on the Status Bar in MobileSafari is not functioning correctly on a specific

I am struggling to troubleshoot this problem with no success so far. The HTML5 JavaScript library I'm developing has a test page that can display a large amount of output by piping console.log and exceptions into the DOM for easy inspection on mobile ...

Create a datastring using a JSON object

When receiving data in JSON format from an AJAX call, the following code is used to parse it: var parsed=JSON.parse(data); An example output could look like this: {"confirm_type":"contract_action","job_id":12,"id":7} To generate a dynamic data string f ...

Why isn't the Nunjucks extends directive functioning when the template is stored in a different directory and being used

I have successfully integrated nunjucks templating into my express app. Below is the directory structure of my project: . nunjucks-project |__ api |__ node_modules |__ views |__ templates |__ layouts |__ default.html ...