Can a component be added with the press of a button?

Let's tackle this challenge together: I have a button that, when clicked, should add my-component to the DOM. If the button is pressed twice, there should be two <p> tags appended. How can I make this happen?

JS:

<script>

  Vue.component('my-component', {
    template: "<p>hello</p>",
  })

  var vue = new Vue({
    el: "#App",
    data: {},
    methods: {
      append: function() {
         // code needed here
      }
    }
  })
</script>

HTML:

<div id = "App">
  <button @click="append" class="btn btn-primary">Spawn stuff!</button>
</div>

Answer №1

Here's a method you can use to achieve that. This script loops through a counter using the v-for directive to iterate over a range.

Vue.component('my-component', {
  template: "<p>hello</p>",
})

var vue = new Vue({
  el: "#App",
  data: {
    hellocount: 0
  },
  methods: {
    append: function() {
      // unknown code here
      this.hellocount++
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ef8fbebcebca0bca0b8">[email protected]</a>/dist/vue.js"></script>
<div id="App">
  <my-component v-for="n in hellocount" :key="n"></my-component>

  <button @click="append" class="btn btn-primary">Spawn stuff!</button>
</div>

This approach is a bit unusual; typically, you would populate the components based on real data, as suggested by @RoyJ in the comments.

As per your request below, you could create a form like this:

Vue.component('my-input', {
  props:["value", "name"],
  data(){
    return {
      internalValue: this.value
    }
  },
  methods:{
    onInput(){
      this.$emit('input', this.internalValue)
    }
  },
  template: `
    <div>
      {{name}}:<input type="text" v-model="internalValue" @input="onInput"> 
    </div>  
    `,
})

var vue = new Vue({
  el: "#App",
  data: {
    form:{
      name: null,
      email: null,
      phone: null
    }
  },
  methods:{
    append(){
      const el = prompt("What is the name of the new element?")
      this.$set(this.form, el, null)
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="790f0c1c394b574b574f">[email protected]</a>/dist/vue.js"></script>
<div id="App">
  <my-input v-for="(value, prop) in form" 
            :key="prop" 
            v-model="form[prop]" 
            :name="prop">
  </my-input>
  
  <button @click="append">Add New Form Element</button>
  <div>
  Form Values: {{form}}
  </div>
</div>

The script creates a form object and generates input fields for each property of the form.

Of course, this is quite basic and only supports text inputs, etc. But I hope you understand the concept behind it.

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

Interactive elements embedded within an image - digital board game

I'm currently working on integrating a board game into React, and I am facing some difficulties in figuring out how to translate the board squares shown in the image into data. Is there a method through which I can assign unique IDs to each square di ...

Import the .obj file along with its original color information, without the need for the accompanying

I am facing a challenge with a .obj file that appears colored in software like MeshLab or Microsoft's 3D builder. However, there is no .mtl file linked to it. When I try to open it in ThreeJs using the most basic method, it shows up as grey. var load ...

Verify if there are any duplicate values in the dropdown menu

I am currently working on a code that adds items to a select list, and it is functioning properly. However, I am facing a challenge in comparing values to prevent duplicates. I know how to compare values, but I am struggling with checking for values that h ...

The angularjs ui-sortable feature is experiencing an issue where methods cannot be called on sortable before initialization. The specific method 'refresh' was attempted to be called prematurely

I'm attempting to sort a list, where I retrieve the elements from a database but... Error: unable to call methods on sortable before initialization; tried calling method 'refresh' This is my HTML: <div class="box-body" > <d ...

Flexbox Resizing Notification(?)

Recently, I've been utilizing flexbox in my layout design and it has been a game-changer. However, I am facing an issue that might be linked to my heavy use of AngularJS, particularly the ng-include feature. The specific problem arises when I incorpo ...

Can a condition be incorporated in a gulpfile to execute a task depending on the size of a file?

Currently, I am utilizing gulp for image compression. However, my requirement is to only compress images exceeding 200kb in size. Can JavaScript be used to loop through a directory and selectively run the minification process on files larger than 200kb? ...

What is the significance of using composability over the deprecated method in Reactjs Material-UI menuItems?

I have taken over a project that was built using an older version of react, and I am currently in the process of updating it. However, I encountered console errors right off the bat. Error : bundle.js:6263 Warning: The "menuItems" property of the "Left ...

Do we still need to configure XSRF-TOKEN on the server even when using HttpClientXsrfModule?

Would implementing the code below in app.module be sufficient to protect against XSRF/CSRF on the client side? HttpClientXsrfModule.withOptions({ cookieName: 'XSRF-TOKEN', headerName: 'X-XSRF-TOKEN' }) Alternatively, is additional ...

Is it possible to include a div above a centered image?

Currently I am working with ImageFlow and I would like to overlay a div on top of the image when it is clicked, sliding it into the center. I have been looking through the JavaScript file but the function MoveIT() seems to be called multiple times and I am ...

Issue with Meteor Vue Tracker not retrieving updated data dynamically

Currently I am using meteor in conjunction with vue, utilizing meteor-vue-tracker for reactive data. Strangely, when returning a collection from the tracker, the data initially comes empty twice before finally showing up on the third attempt. This issue se ...

Extracting a specific variable value from a response by sending a request with CURL command and manipulating the data using JavaScript

Here is my Curl request: curl -u "YOUR_USERNAME:YOUR_ACCESS_KEY" \ -X GET "https://api-cloud.browserstack.com/app-automate/sessions/22dbfb187486090d974a11ac91t65722988e0705.json" This is the Response I received: { "automati ...

How can I define a schema attribute for a controller in Express JavaScript?

Hello, I am brand new to exploring stack overflow and the world of development. I have been self-teaching myself how to code using React and Express, so please forgive me if my question seems basic or implausible. I still have many fundamental gaps in my k ...

After cloning the variable from props, the Vue 3 Composition API variable becomes undefined

I have a main component containing code and tables, including a modal that is displayed based on a boolean value. The main component features the following modal: <ConfirmPaymentModal ref="confirmPaymentModal" :invoice="markAsPa ...

Oops! Looks like we have encountered an issue in three.js: The constructor for Materials[json.type]

I've been developing a web application that displays 3D animated models created in 'Maya 2016'. These models are exported using the three.js (r81) 'maya exporter plugin'. For those interested, you can find the maya exporter plugin ...

Navigate the Angular interceptor route to display a 404 error page when clicking on a `<a href="#">` tag

When using href="#" as a placeholder in html, I encountered an issue where Angular was unable to recognize it and would route to the 404 page despite having the following configuration in the module. How can this problem be resolved? .config( function m ...

React: What is the best way to dynamically render images by iterating through a list?

Currently, I am attempting to iterate through an array of objects. Each object within the staff array in my JSON contains an imgUrl: { "home": { ... "staff": [ { ... "imgUrl": "../Images/Jon ...

What is the best way to map elements when passing props as well?

In my code, I am using multiple text fields and I want to simplify the process by mapping them instead of duplicating the code. The challenge I'm facing is that these textfields also require elements from the constructor props. import React, { Compon ...

Tips for relocating a div panel below all other div panels when a button is clicked with JQuery and CSS

There are several panels stacked below each other. Each panel has a button that, when clicked by the user, should move the panel to the bottom of the stack. For example: If there are 10 panels aligned sequentially and the user wants to remove Panel 2 by ...

Executing a JavaScript function without passing arguments does not yield the desired result

Within my JS file, I encountered an issue when trying to call one function from another. Initially, I called the function with no arguments using only its name handleResponse. However, when attempting to add arguments by changing the function signature, I ...

The Vuetify theme seems to be getting overlooked

I recently created a file in my plugins directory with the following code snippet: import Vue from "vue"; import Vuetify from "vuetify/lib/framework"; Vue.use(Vuetify); export default new Vuetify({ theme: { themes: { light ...