Utilizing children as a prop within a Vue component

In React, I can create a FancyList component like this:

const FancyList : React.SFC<{},{}> ({children}) => (
    <ul>
        {...children}
    </ul>
);

const FancyListItem : React.SFC<{text: string}, {}> ({children}) => <li>{...children}</li>

const App = React.SFC<{},{}> () => (
    <FancyList>
        <FancyListItem>foo</FancyListItem>
    <FancyList>
);

Attempting to accomplish something similar in Vue, I have noticed that passing children around is not the preferred method. Despite my efforts and experimentation, it seems that this approach does not align with Vue's documentation. Here is an example of what I have tried within the parent component. I have registered the FancyListItem component to both the parent and the root. The template code in the parent component looks like this:

<ul>
  <li v-for child in $root.$children>
</ul>

or like this:

<ul>
  <li v-for child in children>
</ul>

In the root, the template code appears like this:

<FancyList>
  <FancyListItem>Some Text</FancyListItem>
  <FancyListItem>Some Other Text</FancyListItem>
</FancyList>

Unfortunately, in either case, I am unable to render anything inside the ul element.

Answer №1

That is correct, the preferred method in Vue is to use slots:

By utilizing slots, you can easily compose components like this:

<navigation-link url="/profile">
  Your Profile
</navigation-link> 

The template for <navigation-link> could look like this:

<a
  v-bind:href="url"
  class="nav-link"
>
  <slot></slot>
</a>

https://v2.vuejs.org/v2/guide/components-slots.html

Answer №2

In Vue, you can achieve this by following the below approach:

customItem.vue:

<template>
  <li>
     <slot></slot>
  </li>
</template>

customList.vue:

<template>
  <ul>
    <slot></slot>
  </ul>
</template>

Main Component:

<template>
  <custom-list>
       <custom-item v-for="item in items" :key="item.id">
          {{ item.text }}
       </custom-item>
  </custom-list>
</template>
<script>
export default {
  components: {
    CustomList: ()=>import('customList.vue'),
    CustomItem: ()=>import('customItem.vue')
  },
  data(){
    return {
      items: [
        //...items
      ]
    }
  }
}
</script>

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

Discovering the specific element that was clicked from a collection of elements

I'm dealing with a scenario where multiple divs share the same class. There is a dropdown that alters the background color of one of these divs when a certain option is selected (for example, option 2 changes div #2's background color). My dile ...

Exploring AngularJS: Retrieving data based on a specific ID from a JSON document

Within my controller class, I extract the ID of a specific user from the URL and pass it on to the OrderService. My goal now is to fetch the data associated with this ID from a JSON file. How can I accomplish this task? OrderCtrl 'use strict'; ...

Determine the value of an object by iterating through its keys

UPDATE: (for clarification) I currently have a table named modelCoa +----+----------+-------+--------------------+ | id | id_parent| code | name | +----+----------+-------+--------------------+ | 1 | 0 | 1 | asset ...

Implement pre-save middleware in Mongoose to perform lowercase validation on a document's

In order to have a user object maintain case sensitivity for display purposes, while being lowercased for uniqueness purposes, I initially considered adding a usernameDisplay property to the schema with a pre-save hook: var userSchema = new Schema({ u ...

I am unable to retrieve the value stored within a function

Below is the code snippet : let namesList = ref([]); const GetFormData = (payload) => { return new Promise((resolve, reject) => { api .get("api.php", { params: { search: payload } }) .then((response) => { data. ...

JavaScript event listener on the "change" event only triggers when changed manually [CodePen]

Check out this jsFiddle I created with all the data and information related to the issue. It should make it easier to understand what's happening: Take a look here: http://jsfiddle.net/lukinhasb/GuZq2/ $("#estado").val(unescape(resultadoCEP["uf"])); ...

No duplication of Collada material present

I imported a collada model (.dae) into Three.js and encountered an issue with the object's material. Ideally, the material should appear as follows: However, it currently looks like this: The color is not an issue; I can modify the lighting within t ...

Having trouble accessing parameter values in a React app using ES6 arrow functions

Hey there! I've been attempting to send values to an ES6 arrow function in my React application, but unfortunately, it's not working. Here's what I'm trying: var data = []; for (var i=1; i<=5; i++) { data.push(<li><a href ...

The smooth shading in Three.js is giving off a flat appearance

When loading .stl files, I'm using MeshStandardMaterial without adjusting the flatShading property since it is set to false by default. https://i.sstatic.net/zbCiR.png The outcome appears rather dull to me. Even when attempting to toggle flatShading ...

Making a POST request using axios in a MERNStack application

After successfully using the express router to add articles with Postman, I encountered an issue when trying to send article information through Axios to MongoDB. Despite no errors appearing in the console, there was a message stating "SharedArrayBuffer ...

I am currently working on creating a drag select feature in React completely from scratch, but I'm facing some challenges with

Check out this code I created for drag selection: Here's the item generation code: const items = [ 1, 2, 3, ...94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, ].map((i) => ({ item: i, selected: i === 1 })); This is the actual code responsi ...

Query MySQL and automatically populate form fields with the data retrieved after the user triggers an "onexit" or "onsubmit" event, all without having to reload the page,

Seeking a way to auto-fill form fields with data from MySQL database. The goal is to input a value in a text field, search the database matching that value, and populate the remaining form fields without having to navigate away from the page. If anyone h ...

Ensuring that a group of items adhere to a specific guideline using JavaScript promises

I need to search through a series of titles that follow the format: <div class='items'> * Some | Text * </div> or <div class='items'> * Some more | Text * </div> There are multiple blocks on the page wit ...

AngularJS can be used to display a webpage

After facing the need to print a given page using AngularJS, I came up with a simple solution as shown below: <div class="modal fade" id="extrait" aria-hidden="true" data-backdrop="false"> <table class="table table-hover table-bordered" i ...

How to send two different types of data using jQuery/AJAX to a .php file? (Syntax)

I am completely new to the world of jQuery/AJAX and I could really use some guidance. Here is the code snippet in question: $(function () { $('.button').on('click', function (event) { event.preventDefault(); //prevents ...

Tips on maintaining the color of the favorite / unfavorite button even after refreshing the page

I am currently developing a Laravel project that allows users to favorite and unfavorite books. When a user clicks on the favorite button, the color changes to red. If clicked again, the color reverts back to gray. The database successfully updates without ...

What exactly happens behind the scenes when utilizing the React hook useEffect()? Is an effect set up with useEffect able to halt the main thread

According to the documentation for the useEffect() hook in React, it states that: "Effects scheduled with useEffect don’t prevent the browser from updating the screen." Insight Unlike componentDidMount or componentDidUpdate, effects set with ...

Using AJAX to send a POST request with the PHP $_FILES superglobal while preventing the default form submission with the onclick

Seeking to implement a photo upload form using an AJAX script that is currently in place. Currently, I have the html form with a file input field. Upon submission, there is an onclick event triggering "PostForm(); return false;" This action directs to a ...

Steps for aligning items in a column horizontally in Bootstrap 5

After creating a Grid system with only 2 columns, I placed text in the first column and a carousel in the second. Despite setting a custom size for the carousel image, I'm facing difficulty centering it horizontally within the column. .title-sec { ...

Rotating an Object3D in Three.js using an axis rotation technique

I am attempting to change the orientation of a mesh that has been loaded into an Object3D using OBJMTLLoader. var obj = new THREE.Object3D(); // loading process... obj.rotation.y += 0.1; //executed within the update function This method works correctly ...