javascript - vue.js 动态添加输入 v-model 不起作用
问题描述
我google了一整天,还没有找到解决这个问题的方法。
我尝试构建应用程序,我可以在其中使用 v-model 插入输入,该输入应该是反应性的,并且此输入的值必须显示在其他div元素中。我真正需要的是有一个代码,我可以使用 v-model 将此输入插入到我的HTML代码中的任何位置。
这是我的迷你应用程序的示例,除了 v-model 不工作外,一切正常,因为我尝试动态插入它。
有谁知道如何使它工作?
这是代码:
<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 = this.numberTypeOne + 1
} 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 = this.numberTypeTwo + 1
}
}
},
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
}
}
}
解决方案
试试这个代码,它对我有用。这是HTML:
<template>
<div>
<input id='inputId' type="text" v-model="inputModel">
<button type="button" @click="create()">Create</button>
<div id='division'> </div>
</div>
</template>
这是方法:
create () {
document.getElementById('division').appendChild(
document.getElementById('inputId')
)
}
v-model 在这里为我工作。
推荐阅读
- mongodb - 有没有更好的方法来构建我的 mongoDB 文档
- r - R表中的粗线,作为对两行进行分组的一种方式
- c++ - 找出对象在其析构函数中的常量
- angular - 无法验证我上传的所有文件
- highcharts - 更改图表标题后,Highcharts userOptions 不更新
- python - Python中的覆盖比较方法
- asp.net-core - 从 Iframe POST 表单时,Asp razor 页面返回 400 代码
- c++ - 如何在 Windows 10 x64 上使用 Bazel 构建和调试 c++ 可执行文件
- java - 为什么 Azure 搜索需要 1400 毫秒才能返回简单查询的查询结果
- javascript - 根据文档,如何与 vuejs 插槽正常执行的操作相反?