Reactivity in Vue on dynamically generated HTML elements

Experimenting with Vue 2, I attempted to generate DOM elements in the mounted hook as shown below:

<div id="app">
  <div id="container">
    <label for="static_name">Existing field</label>
    <input type="text"
           id="static_name"
           v-model="value">
  </div>
</div>

<script>
new Vue({
  el: "#app",
  data: {
    value: 'Example value'
  },
  mounted: function() {
    const container = document.getElementById('container')
    const label = document.createElement('label') 
    const input = document.createElement('input')
    
    label.setAttribute("for", "name")
    label.innerHTML = "Added field"
    input.setAttribute("type", "text")
    input.setAttribute("id", "name")
    input.setAttribute("v-model", "value")  // Utilizing reactivity
    container.append(label)
    container.append(input)
  }
})
</script>

Check out JSFiddle example

The input field labeled "Added field" created within the mounted hook replicates the "Existing field", but unfortunately the v-model directive does not function as expected in the former (unlike the predefined field in the HTML code). It seems that reactive data is not processed properly during the creation stage of the life cycle.

I'm wondering: Is there a workaround or method to incorporate reactive data in dynamically added DOM elements using the createElement API similar to the mentioned scenario?

Currently utilizing Vue 2 but willing to transition to Vue 3 if necessary.

Answer №1

If you are working with Vue, consider using either Vue 2.7, Vue 2.6 with the composition API, or Vue 3. Once you have chosen your version, add a reactive or ref value to your code.

const model = ref('hello')
setAttribute('v-model', model)

watch(model, value=>{
})

Remember to access your value outside of the watcher or template by using model.value.

Alternatively, you may find it more practical to dynamically generate a new Vue component instead.

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

Utilizing a d.ts Typescript Definition file for enhanced javascript intellisene within projects not using Typescript

I am currently working on a TypeScript project where I have set "declaration": true in tsconfig.json to generate a d.ts file. The generated d.ts file looks like this: /// <reference types="jquery" /> declare class KatApp implements IKatApp ...

"Using angularjs's $location.search method results in an empty object being

I am trying to retrieve my URL querystring in AngularJS using the $location service, similar to this example. My URL looks like this - http://someDomain.com/create/index.jsp?queryToken=123abc However, in my directive: vm.queryParam = $location.search(); ...

Creating dynamic URL routes for a static website using Vue

I am facing a challenge with my static site as I am unable to add rewrites through htaccess. Currently, our site is built using Vue on top of static .html templates such as \example\index.html. When I want to create a subpage within this layout, ...

Error: The property 'rows' cannot be read because it is undefined

While working through the steps outlined in Getting started with Postgres in your React app, specifically when processing and exporting the getMerchants, createMerchant, and deleteMerchant functions, I encountered an error that says: "TypeError: Cannot rea ...

When a client sends a GET request to the server, an error occurs due to the absence of 'Access-Control-Allow-Origin' header in

I am encountering an issue with my node/express js application running on localhost while making a 'GET' request to Instagram's api. The error message I keep receiving is: XMLHttpRequest cannot load https://api.instagram.com/oauth/authorize ...

An error occurred with the datepicker: Unable to connect to 'bsValue' as it is not recognized as a property of 'input'

Despite importing DatepickerModule.forRoot() in my Angular unit test, I am encountering the following error: Error: Template parse errors: Can't bind to 'bsConfig' since it isn't a known property of 'input'. (" ...

An issue has been identified where the Export to Excel and PDF functionality is not functioning properly within a Datatable after applying a

I am using multiple select option filtering with ajax, jQuery, and PHP in a datatable. The records are being filtered correctly, but after changing the select option, the Export to Excel/ PDF functionality is not working properly. Note:- (1) It always do ...

Delete auto-generated list using handlebars JS

I have successfully created a dynamic list using Handlebars.js and its template. However, I am now facing confusion on how to remove or delete items from the list using a function or specific code. As I am new to Handlebars, I would appreciate any help. ...

Automatically adjusting the top margin of the main content section depending on the variable height of a fixed header

Visit our mobile site here (mobile view) Currently, I have set the margin-top of .main-content based on sticky-animation, which keeps the header fixed at the top on mobile. However, there is a div with a close button (X) that alters its height dynamically ...

Creating a Blurry Image Effect in Vue.js

Check out this example using Next.js: <Image blurDataURL="/poster.png" src={item.cover_path || defaultImage} alt={item.name} layout="fill" className="next-image" placeholder="[blur][1]" /> Now, how can I ...

LinkButton not triggering on Master Page when accessed from Second Child Page in ASP.NET

I am currently working on a project in ASP.NET (Framework 4.0) where I have implemented an Asp LinkButton in the Master Page that is linked to two different pages (Home.aspx and service.aspx). The question at hand is: The LinkButton1 functions properly on ...

Whenever I try to include something within the `componentWillUnmount` function,

I'm currently learning React on my own. I've been trying to save session data in my componentWillUnmount method. However, when I add code inside componentWillUnmount, nothing seems to happen. I tried debugging by adding console logs and debugger ...

Searching for an object in Vue 3 Composition API and displaying its contents

Experiencing a challenge with my first Vue.js project, seeking assistance in resolving the issue. Upon receiving a response from my API, I retrieve a list of projects and aim to locate the one matching the ID provided in the URL parameter. A peculiar error ...

Switching from using jQuery to Mootools in a short script that helps to balance the heights of

I have a simple script that I frequently use in jQuery to make boxes equal heights. Now, I need to convert it to mootools for a new project where the boxes will be floated left at thirds using style sheets. <div id="box1" class="equals">content he ...

Anomaly observed in the deconstruction of Material UI table components

Utilizing the table component from the Material UI react components library, I encountered a need to incorporate custom behavior into the TableRow. To achieve this, my approach involved breaking down the table and planning to encapsulate it within my own ...

Dynamically alter routing in Express by retrieving route paths from a JSON document

My goal is to dynamically update my route in Express using a JSON file that stores the specific link. The JSON data resides in articles.js and appears as follows: title: 'title1', link: 'title2', creator: 'user1', crea ...

Ways to determine if a user is using a PC using JavaScript

I am developing a website using node.js that will also serve as the foundation for a mobile app. The idea is to have users access the website on their phones and use it like an app. But I want to implement a feature that detects when the site is being vi ...

Dealing with problems in col-md display on tablet devices

When viewing on Full Screen and mobile, the ranges panel (class="col-md-3") displays correctly. However, on tablet screens, the left column is obscured by the youtube image panel (class="col-12 col-md-9"). I have attempted various adjustments to the div s ...

When using JavaScript to dynamically load canvases and create drawing contexts within a function, the context may suddenly disappear

Currently, I am modifying the canvases displayed through ajax calls and also updating what is drawn on each canvas. The primary issue I am facing is that my main drawing function fails on getContext and there are some unusual behaviors such as missing canv ...

Using Javascript to emphasize Ajax Response

I am faced with a challenge of highlighting specific words within text received from an ajax response, before generating HTML code and inserting it into the DOM. At the moment, I am utilizing the following code snippet: function highlightWords(line, word, ...