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

Adding elements to an array in Vue.js using a method

I'm facing a puzzling issue that has left me perplexed My registration form activates a method on blur for every input field; <input class='form-control' placeholder='Username' @blur="watchVal" v-model="username"> The Meth ...

What steps are involved in setting up a local server on my computer in order to create an API that can process http requests from Flutter?

New to API creation here, so please be patient. I plan to eventually host my API on a more robust server, but for now, I want to get started by setting something up locally on my PC to work on backend functions. The API goals include: Verify incoming requ ...

The extjs datecolumn is displaying dates with a one-day discrepancy

My Ext.grid has a datecolumn, but I'm experiencing an issue where the dates displayed are off by one day. The problem seems to be related to timezones, as when data is added to the store it shows up differently later on. For example, 2013-03-31 becom ...

Changing from using GET to employing POST

My current Ajax request function is as follows: // JavaScript function myFunc(pid) { $.ajax({ type : "GET", url : "testback.php", contentType : "application/json; charset=utf-8", dataType : "json", data : { ...

Is there a way to ensure the collapsible item stays in its position?

I'm encountering an issue with the display of items within collapsible cards. Here is what it currently looks like: And this is how I want it to appear: Is there a way to achieve the desired layout using Bootstrap's Grid or Flex Layout? Here i ...

Ways to manage an excessive number of asynchronous calls?

As a newcomer to Node, I've learned that writing synchronous functions can negatively impact the event loop by causing it to lock up. It's generally better to write everything asynchronously. However, there are cases where using async for everyt ...

Remove specific data from jQuery datatables using data attribute

My jQuery datatable is loaded with data from a database without any filtering by default, providing all the necessary information for users. In addition to the built-in search functionality of jQuery datatables, I have incorporated custom search input fiel ...

Transitioning between states in React with animation

In my React application, I have a menu that contains a sub-menu for each item. Whenever an item is clicked, the sub-menu slides in and the title of the menu changes accordingly. To enhance user experience, I aim to animate the title change with a smooth fa ...

Conceal virtual keyboard on mobile when in autocomplete box focus

I would like the keyboard to remain hidden when the autocomplete box is focused or clicked, and only appear when I start typing. The code below currently hides the keyboard when any alphabets or numbers are pressed. However, I want the keyboard to be hidd ...

The operation to set a nickname in Discord.js was unsuccessful due to insufficient permissions

Recently, I started using discord.js to create a simple bot. Whenever I try to change the nickname by calling message.member.setNickname("Another Nickname").then(console.log, console.log); I receive the following error message: { name: ' ...

Tips for sending textarea data via AJAX with TinyMCE

Recently, I encountered an issue with submitting forms using the TinyMCE Jquery plugin. While regular input fields like text fields and select boxes submit just fine, there seems to be a glitch when it comes to submitting a textarea with TinyMCE. It requir ...

Utilizing recursive AJAX requests and halting execution at a specified condition

After hours of searching and attempting, I am struggling as a beginner with ajax concepts. Here is my issue: 1. I have a page that retrieves the current date's data from the database, so I am using an ajax function recursively with a setTimeout of 10 ...

Transforming an array into key-value pairs where the keys are odd elements and the values are even elements

Is there a straightforward way to transform this initial array: [ "Bargain", "deal", "Consistent", "Steady; regular", "Accurately", "a thing bought or offered for sale much more cheaply than is usual or expected.", "Charge", "demand (an am ...

What is the best way to manage the package-lock.json file during deployment from git using SSH?

In my deployment process, I utilize a Git repository to check code in. By using web hooks, a deployment script is triggered on the production server. Once connected to Git via SSH and a .pem key on the server, I perform a Git pull, npm install, webpack bui ...

The client sent a risky Request.Path value that raised red flags

For a university project, I am attempting to access an English translation of the Quran from quran.com using the provided link: Although this link works correctly when entered directly into a browser, I encounter an error when trying to use it in my Angul ...

Unable to input text using Python Selenium in a textbox

Currently, I am attempting to input text into a specific textarea HTML element using Python Selenium: <div class="spk-c spH-d"><div id="gwt-uid-23" class="sppb-a"> <div class="sppb-b spk-b">For example, flowers or used cars</div> & ...

Encountering a ReferenceError: require is undefined error when utilizing contextIsolation: true in conjunction with a preload script

My goal is to implement a select folder popup functionality, and I have written the following code for this purpose. Within the create-window.ts file, I have included these browserOptions.webPreferences: webPreferences: { nodeIntegration: true, conte ...

Tips on setting pre-defined data in a ReactJS form builder field

Currently, I am utilizing the reactjs-form-builder to create forms within a React.js environment. Below is an excerpt of my fields object: this.state = { id: null, loading: true, fields: { "fields&qu ...

Having trouble getting JavaScript to select a stylesheet based on time?

I am attempting to implement two different styles based on the time of day. Here is the code I am using to select the CSS file depending on the current time: <script type="text/javascript"> function setTimedStylesheet() { var currentTim ...

Save a collection of controller instances within a separate controller in AngularJS

I am in need of an angular example where one controller wraps another. For instance, I am looking to divide some logic between EndpointListController and EndpointController. EndpointListController will handle retrieving data from storage, along with funct ...