The issue with v-model on dynamically created inputs in Vue.js

I've spent the entire day searching, but I still haven't found a solution to this issue.

I'm working on an app where I need to use v-model for reactive input that displays its value in another div element. What I really want is to be able to insert this input with v-model dynamically anywhere in my HTML code.

Here's a snippet of my mini app, where everything works fine except for v-model not functioning properly due to dynamic insertion.

Does anyone know how to fix this?

Check out the code below:

<template>
<div>
<div id="content"></div>
<button type="button" @click="createNew('typeOne')">Create Type One</button>
<button type="button" @click="createNew('typeTwo')">Create Type Two</button>

<h3 style="color:#000000;" id="formTypeOne0">formTypeOne0</h3>
<h3 style="color:#000000;" id="formTypeOne1">formTypeOne1</h3>
<h3 style="color:#000000;" id="formTypeTwo0">formTypeTwo0</h3>
<h3 style="color:#000000;" id="formTypeTwo1">formTypeTwo1</h3>

</div>
</template>

<script>
export default {
data () {
  return {
    formTypeOne0: '',
    formTypeOne1: '',
    formTypeTwo0: '',
    formTypeTwo1: '',
    numberTypeOne: 0,
    numberTypeTwo: 0
  }
},
methods:{
  createNew(type) {
    if (type === 'typeOne') {
      var html = '<input type="text" :value="formTypeOne' + this.numberTypeOne + '" v-model="formTypeOne' + this.numberTypeOne + '">'
      document.getElementById('content').insertAdjacentHTML('beforeend', html)
      this.numberTypeOne++
    } else if (type === 'typeTwo') {
      var html2 = '<input type="text" :value="formTypeTwo' + this.numberTypeTwo + '" v-model="formTypeTwo' + this.numberTypeTwo + '">'
      document.getElementById('content').insertAdjacentHTML('beforeend', html2)
      this.numberTypeTwo++
    }
  }
},
watch: {
  formTypeOne0: function(val, oldVal) {
    document.getElementById('formTypeOne0').innerHTML = val
  },
  formTypeOne1: function(val, oldVal) {
    document.getElementById('formTypeOne1').innerHTML = val
  },
  formTypeTwo0: function(val, oldVal) {
    document.getElementById('formTypeTwo0').innerHTML = val
  },
  formTypeTwo1: function(val, oldVal) {
    document.getElementById('formTypeTwo1').innerHTML = val
  }
}

}

Answer №1

Give this code a try, it successfully worked for me. Below is the HTML snippet:

<template>
<div>
<input id='inputId' type="text" v-model="inputModel">
<button type="button" @click="create()">Create</button>
<div id='division'>  </div>
</div>
</template>

Additionally, here is the method used in the code:

  create () {
    document.getElementById('division').appendChild(
      document.getElementById('inputId')
    )
  }

The usage of v-model turned out to be effective for my case.

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

Switch between showing or hiding at least three divs

I'm currently using a simple script that toggles the visibility of two div elements: <script type='text/javascript'> $(window).load(function(){ function toggle_contents() { $('#page1').toggle(); ...

Custom dropdown selection using solely JavaScript for hidden/unhidden options

I'm trying to simplify things here. I want to create a form that, when completed, will print the page. The form should have 3-4 drop-down lists with yes or no options. Some of the drop-downs will reveal the next hidden div on the form regardless of th ...

Transfer data in scripts to dynamically load Ajax pages

Is there a way to send variables or parameters from the original page to a script tag on another page that is loaded using jQuery Ajax? Here are the scripts: Page 1 <script> $(function(){ $('#button').click(function(){ $.ajax({ type:"P ...

"Explore the Hong browser designed specifically for enhanced Ajax functionality

I made the decision to revamp my new job by incorporating Ajax into the mix. Here is the code snippet I used to load pages: html <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> <link rel="stylesheet" ...

The _.get function is not compatible with the module.exports object

After exporting an object from a node file, my code is not functioning as expected. (path './../../config/cloud.js): module.exports = { some: { property: 1 } } Even though I am using the following code: const config = require(&ap ...

Navigating through this object with PUG and Express: a step-by-step guide

I am currently working on a basic blockchain project to practice my skills with nodejs. I have created a blockchain object that consists of a block class, and now I want to loop through this object using pug. app.get('/', function(request, respon ...

What is the process for connecting my Stripe webhook to my Heroku application?

After successfully integrating Stripe into my JavaScript app and testing it with ngrok in the development environment, I encountered a timeout issue when switching to the production environment. Users are unable to proceed from the Stripe checkout screen. ...

When utilizing Vuetify, I encountered an issue where attempting to print a page resulted in only the first page being displayed

My app utilizes the Vuetify framework. One particular page is dedicated to orders, and I'm looking to enable users to print it. The issue arises when there is a scroll on the page - only the first page gets displayed with a scrollbar: https://i.sta ...

Customize Link Appearance Depending on Current Section

Looking for a way to dynamically change the color of navigation links based on which section of the page a user is currently viewing? Here's an example setup: <div id="topNav"> <ul> <li><a href="#contact">Contac ...

Issue with background overlapping

I am currently creating a questionnaire that consists of 10 questions and calculates a score called total. If the total < 10, I want the screen to turn red. However, this required me to remove the previous wallpaper that was set: /*body{ backgr ...

The Vue.js checkbox linked to a v-model with a value set to false is currently marked as

I'm attempting to create a to-do list resembling the Eisenhower matrix, but I'm encountering an issue with v-bind and v-model being triggered incorrectly. How can I resolve this bug? https://i.sstatic.net/iIhqR.png Code inspiration from Vue.js T ...

The functionality of the calculator, created using HTML and JavaScript, is impeded on certain devices

I developed a web-based app that functions as a simple calculator for calculating freight/shipping prices to Venezuela. The app allows users to select between 1 to 4 packages, and choose different types of freight including air (normal, express) and mariti ...

Close the overlay by clicking outside of it

I'm working on creating a unique pop-up window that appears when a customer adds a product to their cart. The design features red and green background divs with a darker overlay (#overlay-daddy) and a white child div (#overlay). My issue arises from ...

Utilizing a switch statement for efficiently loading multiple objects within a Three.JS framework

Currently, I am working on a web 3D model viewer that utilizes Three.JS. My goal is to enable users to select different models from a dropdown list using dat.GUI. To achieve this, I have been experimenting with a switch statement, drawing inspiration from ...

When you try to remove an element from an array by its index in Vue JS, the outcome may not be

Here is an array that I have: var hdr = ("name", "date", "start_time", "selling_item", "total_call", "end_time", "ad_num", "area", "order_num"); //this data comes from the database Now, I need to rename these array elements according to prope ...

Discovering the amount of time a section of a webpage remains in view on a browser

I am looking for a way to track user engagement on my website that contains pages with extensive scrolling and numerous images. Each user who logs in sees a unique selection of images. My goal is to monitor how long users linger on each part of the page t ...

When conditions are met, all items are added to the array

In my Angular app, I have a user list that I am trying to filter based on the condition age > 45. However, all users are being pushed into the validForScheme array instead of just those meeting the condition. I am unable to figure out what is going wron ...

Tips for acquiring an object to utilize in v-bind within a v-for loop

Consider this code snippet: <ol class="breadcrumb arr-right"> <li v-for="(url,name, index) in links" v-bind:class=" (index == (links.length -1)) ? 'breadcrumb-item active' : 'breadcrumb-item'"> <a v-bind:href ...

Modify the color of the field that is currently chosen

Is there a way to modify the highlight color of the active record in an extjs combobox? In the image provided below, the record Petty Cash Fund is currently selected in my dropdown, but the highlighting is not very visible. How can I adjust this for all co ...

What is the process for creating a button click listener event in Kotlin or JavaScript?

While working in IntelliJ IDEA, I have created a button in my HTML file with an ID. My goal is to change the header tag to say "button clicked" using Kotlin. After searching through kotlinlang.org and other resources, I am struggling to find a simple refe ...