Encasing newly inserted child components within my designated slot

If I have a component with a single slot and instead of simply rendering all its children, I want to wrap each element individually, the following approach can be taken:

Vue.component('MyElement', {
  render: function(createElement){
      for (let i = 0; i < this.$slots.default.length; i++) {
      // Create a wrapper element
      let wrappedElement = createElement("div", {}, this.$slots.default[i]);
      // Replace the current element in this slot with the wrapped element
      this.$slots.default[i] = wrappedElement;
    }

    return createElement("div", this.$slots.default);
  }
}

Usage example:

<MyElement ref="myElement">
  <p>Item 1</p>
  <p>Item 2</p>
</MyElement>

Resulting in the following structure:

<div>
  <div>
    <p>Item 1</p>
  </div>
  <div>
     <p>Item 2</p>
  </div>
</div>

So far, everything works as intended.

However, when attempting to dynamically insert another <p> element into <MyElement> using

// Get reference to <MyElement>
const myElement = this.$refs["myElement"];
// Create a new element
var newElement = document.createElement("div");
newElement.innerText = "Hiya";
myElement .$el.appendChild(newElement);

The new element will not be wrapped because the render method is not invoked again. Is there a way to take full control of rendering for each child in the slot or perhaps a better method to programmatically append children into a component?

Thank you.

Answer №1

If you're looking to streamline the process of adding new items, one solution could be creating a customized component for each item. By implementing a method that triggers the item component when needed, you can easily add new items in the future.

I have prepared a Code Snippet as an example:

Vue.component('CustomElement', {
  template: '#element-container',
});

Vue.component('CustomElementItem', {
  template: '#element-item',
  props: {
    innerText: {
      type: String,
      default: '',
    }
  }
});

new Vue({
  el: '#app',
  data() {
    return {
      items: ['Item 1', 'Item 2', 'Item 3'],
    }
  },
  methods: {
    // You can create a method here to add more items and trigger the CustomElementItem component.
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <custom-element>
    <custom-element-item v-for="(item, index) in items" :key="index" :inner-text="item" />
  </custom-element>
</div>

<script type="text/x-template" id="element-container">
  <div>
    <slot></slot>
  </div>
</script>

<script type="text/x-template" id="element-item">
  <div>
    <p>{{ innerText }}</p>
  </div>
</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

Downsides of utilizing variables as global entities in React components

I am currently working on integrating API data into my React component: const request = new XMLHttpRequest() let outputArray = [] request.open('GET', 'http://localhost:3005/products/157963', true) request.onload = function() { let d ...

The error occurred while trying to cast the value of "{{Campground.name}}" to an ObjectID. This value, which is of type string, could not be converted to an ObjectID at the path "_id" for

const express = require("express"); const session = require("express-session"); const cookieParser = require('cookie-parser') const mongoose = require("mongoose"); const { Campground, User, Review } = require(" ...

Can config values be dynamically set from an Excel file in Protractor?

I am currently working on parameterizing capabilities using an Excel sheet. For this task, I am utilizing the npm exceljs package for both reading and writing data. Below is a snippet of the code that demonstrates how I am trying to achieve this: //This f ...

Positioning the filters in jQuery Datatables

I'm currently working with jQuery datatables and I'm attempting to align the filter/search box on the same row as the header of the container holding the datatable. Attached is a screenshot for reference: https://i.stack.imgur.com/nzbIl.png He ...

Attempting to generate a cost estimator, however, no results are showing up upon clicking the calculate button

Having based my code on a template and being fairly new to Javascript, I expected everything to work smoothly. However, upon testing it, I encountered an issue where nothing was displayed in the results boxes. My goal is to develop a pricing calculator th ...

Executing a function from another reducer using React and redux

My application consists of two main components: the Market and the Status. The Status component manages the user's money, while the Market component contains buttons for purchasing items. My goal is to decrement the user's money when a button in ...

The method to permit a single special character to appear multiple times in a regular expression

I am currently working on developing a REGEX pattern that specifically allows alphanumeric characters along with one special character that can be repeated multiple times. The permitted special characters include ()-_,.$. For instance: abc_def is conside ...

Reset the input field once the message has been successfully sent

My goal is to clear the form message input field after the form is sent. However, it seems to be clearing the data before it has a chance to be sent. Here is the code I'm using: <script> $(function () { $('form#SendForm'). ...

Want to learn about Google Apps Script Web App? Join us to dive into AJAX, leverage

I'm attempting to follow the steps outlined in "Example 3: Web Response" on "this SparkFun tutorial" After implementing the code on script.google.com, I encountered an issue where I couldn't see the pin readings. Can someone provide assistance w ...

Is it normal for the protractor cucumber tests to pass without observing any browser interactions taking place?

Having recently started using protractor cucumber, I have created the following feature. Upon launching protractor protractor.conf.js, the browser opens and immediately closes, displaying that my tests have passed. Is this the expected testing behavior? Sh ...

Retrieve the designated element from an array of JSON data in SPLUNK

As a newcomer to the world of Splunk, I am facing a challenge with handling JSON data. Here is an example of the JSON data I am working with: "request": { "headers": [ { "name": "x-real-ip", "value": "10.31.68.186" ...

.fetchevery(...).then has no function

I recently upgraded Angular to version 1.6.4. As a result, I made changes to the code by replacing .success and .error with .then However, now I am encountering the following error: An unexpected TypeError occurred: .getAll(...).then is not a function ...

Instead of modifying the selected class, jQuery generates inline styles

Utilizing the following code to dynamically create a class: $("head").append('<style type="text/css"></style>'); var newStyleElement = $("head").children(':last'); newStyleElement.html('.move{transform: translateX(1 ...

How do I automatically redirect to a different URL after verifying that the user has entered certain words using Javascript?

I want to create a function where if a user input on the "comments" id matches any word in my FilterWord's array, they will be redirected to one URL. If the input does not match, they will be redirected to another URL. The checking process should onl ...

The process of AJAX polling a JSON-returning URL using jQuery's $.ajax() method does not appear to provide up-to-date responses

I am currently working on a project that involves polling a specific URL for a JSON response using AJAX. The initial AJAX request alerts the server of my need for JSON content, prompting it to start building and caching the response. Subsequent AJAX reques ...

Master the art of utilizing ENV Variables in vue-cli to optimize your development workflow

Recently, I delved into Vue-Cli for the first time while following a tutorial on pairing a Vue frontend with a Rails backend. In the process, I'm configuring Axios to manage my requests. The challenge I'm facing is when attempting to define an E ...

Guide to activating form elements using a JQuery function

I need help setting up a form with 11 rows and 11 columns. By default, the form fields should be disabled, but when I click on an "EDIT" button, they should become enabled. Any assistance would be greatly appreciated. Thank you in advance. Here is my edit ...

Tips for utilizing a function within a callback function using jQuery

When using jQuery's .load() to load HTML files into a parent webpage, I am interested in executing jQuery/JS from the parent page against the loaded HTML file. It seems like this can be achieved with a callback function. The jQuery I'm using is ...

React not showing multiple polylines on the screen

I'm currently working on an application aimed at practicing drawing Kanji characters. To draw the lines, I'm utilizing svg. The issue I've encountered is that when I try to draw multiple separate lines using a 2D array of points for each lin ...

Firefox 3 fails to utilize cache when an ajax request is made while the page is loading

Upon loading the page DOM, I utilize jQuery to fetch JSON data via ajax like so: $(document).ready(function(){ getData(); }); ...where the function getData() executes a basic jQuery ajax call similar to this: function getData(){ $.ajax({cache: t ...