How can I send data to components that are dynamically added?

Recently, I put together a test on a codepen that allows me to dynamically add components to an existing page. However, the challenge lies in passing props to these components. While browsing through another question, I found someone else struggling with a similar issue related to dynamic component switching during runtime in Vue.js.

I am aiming for the ability to generate a component on-the-fly by clicking a button, like this:

  • <button-counter :input="'TestText'"></button-counter>
  • <vue-header :input="'TestText'"></vue-header>

Currently, I can create components dynamically without passing any props. So specifying 'button-counter' or 'vue-header' will successfully generate the component, although it won't be configured with any props (this applies to all components).

Answer №1

I made a few tweaks to your Codepen project on my own version located here. You were almost there!

The key alteration lies in how the children are handled and how we incorporate a dynamic component.

Original

const App = new Vue({
  el: '#app',

  data: {
    componentName: "componentName",
    input: "input",
    children: [
      buttonCounter,
      vueHeader
    ]
  },

  methods: {
    add () {
      this.children.push(this.componentName)
    },
  }
});

Modified

const App = new Vue({
  el: '#app',

  data: {
    componentName: "componentName",
    input: "input",
    children: [
      { componentName: 'button-counter', input: 'I am a button' },
      { componentName: 'vue-header', input: 'I am a header' }
    ]
  },

  methods: {
    add () {
      this.children.push({ 
        componentName: this.componentName, 
        input: this.input 
      })
    },
  }
});

Also, adjustments need to be made to the v-for loop within your template to accommodate the updated structure of the children array:

<template v-for="(child, index) in children">
  <component :is="child.componentName" :input="child.input" :key="child.name" />
  <br>
</template>

By transforming your children into an object array capable of accepting various props, you can effortlessly pass those same props into the dynamic component. In this scenario, both custom components have a prop named input as part of the object array definition.

An important thing to highlight is that when it comes to Dynamic Components in Vue.js, the is property can either receive the component itself (as per your original method) or a string representation of a pre-registered component. This distinction sets apart your initial implementation from my modified version.

Hope this helps!

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

Retrieve Vuejs template by either module or ID

In my .Vue file, I have defined a template along with its subcomponents with the intention of allowing customers to override this template without needing to modify any javascript code. If there exists an element with id="search-result", then that element ...

Vue.js encountered an uncaught TypeError while trying to execute the 'drawImage' function

I am facing an issue with my vue.js application where I can successfully apply a filter to a photo, but I am unable to post it. The error message I am encountering is: Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingCon ...

Learn how to access the checkbox event.target.checked and event.target.value properties in Vuetify

How can I retrieve the checked status and value of a Vuetify checkbox using event.target.checked and event.target.value? In my application, I am utilizing Vuetify's checkbox component. When the user interacts with the checkbox by checking or unchecki ...

Unable to transfer all the formatting from the original file for the window.print() function. Localhost is functioning properly, but encountering issues with production

I'm encountering an issue with getting all styles from my Vue app. I have tried the code provided in this answer: https://stackoverflow.com/questions/52343006/how-to-print-a-part-of-a-vue-component-without-losing-the-style While it works fine on loc ...

Vue - a guide on customizing a prop in a parent component

I have implemented a wrapper component that encapsulates a Quasar q-select element in the following manner: <template lang="pug"> q-select( :options="organisations" option-value="id" v-bind="$attrs&quo ...

Exploring the dynamic data loading feature in Vue 3 by fetching data from the server and displaying it using a v-for

I am encountering an issue where I want to display data dynamically from a database using a v-for loop. However, when I attempt to push new data into the array, they show correctly in a console.log() but do not reflect any changes in the template. I have ...

Utilizing Cypress with Electron: A Guide to File System Operations

I have been utilizing Cypress to run tests on my Electron application. Due to Cypress operating in browser mode, the FS module is not compatible. As a result, I am encountering this error: Error in mounted hook: "TypeError: fs.existsSync is not a func ...

I'm encountering an issue with enabling Node.js support on PhpStorm as it keeps freezing at the dialog box. Does anyone have a solution for this problem?

Seeking assistance with configuring code support for Vue files in PhpStorm v10.0. Despite having Node and Vue plugins installed, my laptop also has Node(v10.16.3) downloaded. Encountering an issue where PhpStorm freezes at a dialog box, as shown in the sc ...

Trigger a re-render of VueTable2 within the child component

My current setup involves a customer component that contains a child component with a vuetable 2. I am in need of a way to refresh the table whenever a new customer is created or updated in the parent component. I was considering using $emit on the parent ...

The initial drag function seems to be dysfunctional in vue-smooth-dnd for vuejs

Check out the code snippet below for a drag and drop section. The div with the class drag-block should be draggable, but it doesn't work on the first attempt; it only drops when we drag it for the second time. https://github.com/kutlugsahin/vue-smoot ...

What is the process for switching the default font in Vuetify from Roboto to a different typeface for all elements?

Is there a way to update the font for all elements in Vuetify from Roboto to another option? I am currently using Vuetify, which comes with the default Roboto font. However, I would like to switch it to a different font. Modifying the font in the variable ...

Display various MongoDB datasets in a single Express route

I currently have a get method in my Express app that renders data from a MongoDB collection called "Members" on the URL "/agileApp". This is working fine, but I now also want to render another collection called "Tasks" on the same URL. Is it possible to ...

Include a search bar for vue2-leaflet package

Does anyone have samples of code for adding a search bar to a vue2-leaflet map? I tried using the vue2-leaflet-geosearch package but encountered issues. Any alternatives or solutions would be greatly appreciated. Thank you in advance. <template> ...

When utilizing Vuetify's v-menu feature, only the initial click will trigger the menu display

 The Challenge I'm Facing Currently, I am developing a calendar using Vuetify and integrating drag-and-drop functionality along with event clicking. One key feature I added is the ability to change event color through a v-menu popup that appears up ...

An issue occurred in the callback function for the watcher "get_settings": "A TypeError was raised because the property 'general' cannot be read

I'm really struggling with handling this error in Vue, especially since I'm new to it. Here's what's happening: I fetch data from the server using a vuex store action. In my component, I access that data using a getter in a computed pro ...

Concealing Rows Once a Specified Threshold of Rows Has Been Modified

My knowledge of Javascript is very basic and I am new to coding. I have created a table that updates when a button is clicked. However, I am looking for a way to limit the number of rows in my table. For example, when I add a sixth data entry to the table, ...

Is it possible to use Vuelidate to require either input field 1 or input field 2 with an "or" validator?

I'm trying to incorporate Vuelidate into my Vue Form. Within this form, I have Phone Number and Email fields. My goal is to validate if either of them is filled out using the "Or" Validator, but unfortunately, I haven't been able to find any exam ...

The CORS policy has blocked the AWS API Gateway request originating from 'http://localhost:8080'

Currently, I am facing an issue with deploying an API for use in Front End. The API functions properly when tested alone, but it returns a CORS error when integrated into a Vue app. The specific error message is as follows: Access to XMLHttpRequest at &a ...

What is the best way to access the index in a v-for loop in Vue.js?

Here is an example of my Vue component: <div v-for="item in items" :key="I need to access the index of the for-loop here" > </div> ... data(){ items: [{name:'a'}, {name:'b'}...] } Is there a way to retrieve the inde ...

Unlock the power of VueJS with advanced checkbox toggling for array data

I have encountered an issue while working with VueJS regarding the implementation of two features for a set of checkboxes. Initially, the checkboxes are generated dynamically. I am in need of a master 'toggle' checkbox that can toggle the stat ...