In what way can a container impact the appearance of a child placed in the default slots?

Visiting the vue playground.

The main goal is for the container component to have control over an unspecified number of child components in the default slot.

In order to achieve this, it's assumed that each child component must either hold a property or identify itself to the parent container.

What would be the best approach for the container to modify the display property of a specific component within the default slot?

Please note there is a relevant query on How can a container change the CSS display property of a child in the default slots?, which focuses on using CSS as a solution to the same issue.

App.vue

<script setup>
import Container from './Container.vue'
import ChildA from './ChildA.vue'
import ChildB from './ChildB.vue'
</script>

<template>
    <Container>
        <ChildA />
        <ChildB />
    </Container>
</template>

Container.vue

<script setup>
import { useSlots, useAttrs, onMounted} from 'vue'

const slots = useSlots()

function logSlots(where) {
  console.log( `${where} slots`, slots )
  const children = slots.default()
  console.log( `${where} slots children`, children.length, children )
}

logSlots("setup")

function changeDisplay(whichChild, show) {
  console.log( "change display", whichChild, show)
  // how can I know I am accessing child a?
  // what goes here?
}

onMounted( () => {
  logSlots("onMounted")
})
</script>

<template>
  <button @click="logSlots('button')">log slots</button>
  <button @click="changeDisplay('child a', false)">Hide Child A</button>
  <button @click="changeDisplay('child a', true)">Show Child A</button>

  <slot />
</template>

ChildA.vue

<script setup>
</script>

<template>
  <div>
    ChildA
  </div>
</template>

ChildB.vue

<script setup>
</script>

<template>
  <div>
    ChildB
  </div>
</template>

Answer №1

To hide the children of the default slot, you have the option to do so by name, reference, or index:

VUE SFC PLAYGROUND

<script setup>
import { useSlots, reactive} from 'vue';
import ChildA from './ChildA.vue'
import ChildB from './ChildB.vue'
const slots = useSlots();
const slotted = () => slots.default().map(vnode => hide.has(vnode.type.name) ? null : vnode);
const slotted2 = () => slots.default().map(vnode => hide.has(vnode.type) ? null : vnode);

const hide = reactive(new Set);


function changeDisplay(whichChild) {
  hide.has(whichChild) ? hide.delete(whichChild) : hide.add(whichChild);
}

</script>

<template>
  <button @click="changeDisplay('ChildA')">Toggle Child A</button>
  <button @click="changeDisplay('ChildB')">Toggle Child B</button>
  <slotted />
  <button @click="changeDisplay(ChildA)">Toggle Child A</button>
  <button @click="changeDisplay(ChildB)">Toggle Child B</button>
  <slotted2 />
</template>

An interactive illustration:

VUE SFC PLAYGROUND

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

What could be causing these transformed canvases to not display fully in Chrome at specific resolutions?

fiddle: https://jsfiddle.net/f8hscrd0/66/ html: <body> <div id="canvas_div"> </div> </body> js: let colors = [ ['#000','#00F','#0F0'], ['#0FF','#F00','#F0F&a ...

Troubleshooting: How to resolve the issue of "Error [ERR_HTTP_HEADERS_SENT]: Unable to set headers after they have been sent to the client"

* **> const PORT=8000 const express = require('express') const {v4:uuidv4}=require('uuid') const bcrypt =require('bcrypt') const jwt =require('jsonwebtoken') const cors=require('cors') const {MongoClie ...

Deleting lines from JSON object using Angular or JavaScript

On my webpage, I have a list where you can add a new line by pressing the "+" button (easy with push), but I'm not sure how to remove lines using the "X" button. https://i.stack.imgur.com/nm06A.png This is the JSON structure: "priceExtra" : [ ...

Trying to filter out repetitive options in an autocomplete box

Using the jQuery autocomplete plugin, I am trying to display 5 unique search results. Initially, I achieved this by limiting the stored procedure to return only 5 results, but now I want to remove duplicates while still showing 5 distinct results. I'm ...

Filtering for Material Autocomplete is limited to the getOptionLabel field

Currently, I am utilizing the Google Material-UI autocomplete component. It is currently only filtering based on the "getOptionLabel" option field when text is entered into the input field. However, I would like the autocomplete to filter based on more tha ...

Concealing the vue.js template until the rendering process begins

I'm working on a method to conceal the contents of the vue.js template until it's completely rendered. Take a look at the template below: <div class="loader"> <table class="hidden"> <tr v-for="log in logs"> <td& ...

When moving from Babel version 5.8.35 to 6.0.0, be prepared for app.js to throw a SyntaxError and encounter an unexpected token during compilation

Currently, I am in the process of enhancing my ReactJS components using webpack. However, I have encountered a hurdle while trying to transition from babel version 5 to 6. Upon attempting the upgrade, it resulted in a stack trace error within my app.js cl ...

"Utilize Bootstrap Modal to load dynamic content with Ajax and incorporate loading

When I use the Bootstrap Modal to load content from another page, the data is quite complex with multiple queries and dynamic forms. As a result, when the modal opens, it tends to get stuck momentarily. I am looking for some sort of animation or indicator ...

Obtain a file from React Native in order to upload an image, just like using the `<input type="file" onChange={this.fileChangedHandler}>` in web development

After experimenting with different methods, I attempted to achieve the desired result by: var photo = { uri: uriFromCameraRoll, type: 'image/jpeg', name: 'photo.jpg', }; and integrating axios var body = new FormData( ...

Display JavaScript and CSS code within an Angular application

I am working on an Angular 1.x application (using ES5) where I need to display formatted CSS and JS code for the user to copy and paste into their own HTML file. The code should include proper indentations, line-breaks, etc. Here is a sample of the code: ...

Content formatted with a gap

I wish to include a gap between each sample usage with markdown. For instance: .kick Sarah, .kick John, .kick Mary .setDescription(`**Usage :** \`${settings.prefix}${command.help.name} ${command.help.usage}\`\n**Example :** \`${setting ...

Execute location.replace when the "control" key is pressed

document.addEventListener('keydown', (event) => { var name = event.key; var code = event.code; if (name === 'Control') { location.replace(classroom.google.com) } if (event.ctrlKey) { alert(`Combinatio ...

Update the variable in a PHP script and execute the function once more without the need to refresh the page

Hey there, I'm wondering if AJAX is necessary for the functionality I want to implement. Here's the scenario: I have a function that generates a calendar and I plan to add 'forward' and 'backward' arrows so users can navigate ...

Having trouble with either posting a JSON using $.ajax() or reading it using PHP?

I'm struggling to identify the issue at hand. Here's my JavaScript function for sending JSON data: function send(var1, var2) { var result; att = window.location; $.ajax({ 'crossDomain': true, 'type&apos ...

Ending a timer from a different function in a React component

Currently, I am delving into the world of React and attempting to create a timer component. While I have successfully implemented the start function for my timer, I am now faced with the challenge of stopping the timer using an onclick handler from another ...

Ramjet: Unveiling the Magic of Making Elements Appear and Disappear

Currently, I am attempting to implement the code for ramjet from . However, I am facing an issue where element a does not disappear when transitioning into b. Additionally, I am encountering an error message "--Uncaught TypeError: Cannot read property &apo ...

What is the best way to showcase a single <ul> list in an infinite number of columns?

Utilizing Django on the backend, I aim to showcase the list below in an unlimited number of columns with overflow-x: auto. <ul class="list"> {% for i in skills %} <li>{{i}}</li> {% endfor %} </ul> Example Result: 1 7 ...

Should a MEAN stack app require the use of two servers in order to run?

Currently, I am in the process of developing a MEAN stack application which involves using MongoDB, ExpressJs, Angular 6, and NodeJs. One issue I am facing is determining whether two servers will be necessary to run the app simultaneously. Specifically, o ...

"Enhance your HTML table by selecting and copying cell values with a simple click and CTRL +

I stumbled upon a fantastic script for highlighting HTML table rows and it's working perfectly: I decided to modify the onclick event to onmouseover and included additional code to select a cell by clicking on it. Now I can select, check which one is ...

Retrieve information from a changing HTML table

I am working on a nodejs express project that features a Dynamic Table within my application. Users can add or remove rows and enter values into cells, but I am struggling to extract these values from the table without using jquery. My goal is to then inse ...