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>
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.