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

The jCapSLide Jquery Plugin is experiencing compatibility issues in Chrome browser

While this JQuery plugin works perfectly in Internet Explorer and Firefox, it seems to be malfunctioning in Chrome. The plugin is not being recognized at all by Chrome, and the captions are appearing below the image instead of on top with a sliding effect. ...

Differences between code executed during compilation and code executed during runtime

As a newcomer to Vue and Webpack, I recently created a static web app using vue-cli and have been experimenting with it. In the file src/components/hello.vue, I came across this code snippet: export default { name: 'hello', data () { ret ...

"Encountering a mysterious internal server error 500 in Express JS without any apparent issues in

My express.js routes keep giving me an internal server error 500, and I have tried to console log the variables but nothing is showing up. Here are the express routes: submitStar() { this.app.post("/submitstar", async (req, res) => { ...

Nuxt.js: Streamlining multiple websites/domains within a single project

Imagine a scenario where we have three distinct websites named website A, website B, and website C. Each of these websites will reside on their own domain, namely mypage-a.com, mypage-b.com, mypage-c.com. The framework that is being utilized here is nuxt.j ...

Notifying the chosen option using jQuery

I have been attempting to display an alert on the webpage based on the selected option. Unfortunately, it appears that my code is not functioning properly. This is what I have tried: $(document).ready(function(){ $("select.country").change(functio ...

Mastering the A-Frame Game Loop: Tips for Separating Logic and Rendering

Currently, I am experimenting with A-Frame and my Quest 2 headset in order to create a simple VR game. One particular challenge I am facing is understanding how to separate logic from rendering and establish a proper game loop. After discovering this tutor ...

Dynamic views loaded from ui-router can cause compatibility issues with running Javascript

Currently, I am facing an issue while attempting to load a template into a UI-View using UI-Router. Although the JavaScript is loaded, it does not run on the loaded views. The situation unfolds as follows: I have developed a template in HTML containing all ...

When scrolling, use the .scrollTop() function which includes a conditional statement that

As a newcomer to jQuery, I've been making progress but have hit a roadblock with this code: $(window).scroll(function(){ var $header = $('#header'); var $st = $(this).scrollTop(); console.log($st); if ($st < 250) { ...

What is the best way to eliminate blank values ("") from an array?

I am working with a two-dimensional array that was generated from an HTML table using jQuery, but I have noticed that some values are empty and are displaying as "". How can I go about removing these empty values from the array? <table> ...

Performing AJAX requests to dynamically update multiple DIVs

Encountering difficulties with adding additional input fields to a page, each of which contains jquery code for appending more select boxes related to them. The base html setup is as follows: <p id="add_field"> … </p> <div class="show_sub ...

Using Javascript to refresh an image and update a class within a DIV when another DIV is clicked

I have a code that is quite lengthy to share here, so I've created a demo on JSFiddle: http://jsfiddle.net/Emily92/5b72k225/ This particular code takes a random image and divides it into multiple sections based on the class applied to the div contain ...

Click event not triggered when transitioning to Service section in Thinkster tutorial

I've been following a tutorial on MEAN stack development () and I encountered an issue after incorporating Angular Services. For some reason, the function incrementUpvotes stopped working and I'm struggling to identify the cause. Since I'm r ...

The functionality of Slick.js is compromised when the v-for directive is refreshed

Hey there! I recently worked on a project using VueJS and slickjs. Everything was running smoothly until I encountered an issue with the slick carousel when updating data in a v-for loop via an AJAX request triggered by a click event. The new data is sto ...

Strategically bypassing the third step to directly progress to the fourth step

Here's my code snippet in vue.js where I'm attempting to skip from the third step to the fourth step in a multi-step form. Essentially, if we're on the second step and press the next button, it should directly take us to the fourth step, byp ...

Implementing a New Port Number on a ReactJs Local Server Every Time

As a newcomer to ReactJS, I recently encountered an issue while working on a project that puzzled me. Every time I shut down my local server and try to relaunch the app in the browser using npm start, it fails to restart on the same port. Instead, I have ...

A step-by-step guide to incorporating expandable and collapsible images within a div element using X

I have successfully created dynamic divs with some data that expand and collapse perfectly. Now I am looking to add expand and collapse images on these divs. I am relatively new to designing in xslt. <xsl:template match="category[key!='org.model.C ...

How can you refresh a functional component using a class method when the props are updated?

I've created a validator class for <input> elements with private variables error, showMessage, and methods validate and isOk. The goal is to be able to call the isOk function from anywhere. To achieve this, I designed a custom functional compone ...

Using JSON with PHP to send data and receiving the response back with JavaScript

Despite exploring numerous questions and attempting various methods, I have been unable to find a solution that works. Here is my JavaScript file: function sendData() { var jsondata; var j = {"pub_id":"'+pid+'","a_type":"'+a_t&ap ...

Switch out external CSS stylesheets automatically using toggle scripting

Hello there! I've been trying to figure out a way for this script to switch back to the original CSS external stylesheet. Here is the code that I currently have: $(document).ready(function() { $("#css-master2").click(function() { $("link[title=chang ...

Incorporating a variety of classes by utilizing loops

Looking to add a class to specific li elements - the 1st, 4th, and 7th, the 2nd, 5th, and 8th, and the 3rd, 6th, and 9th. Is this possible? Is there a way to achieve this? ...