繁体   English   中英

如何使用输入字段替换文本中的占位符,并使用Vue.js将它们与v-model绑定

[英]How to replace a placeholders from a text with input fields and bind them with v-model with Vue.js

我正在建立一个包含测试题的考试页面。 问题来自“填补空白”类型。 我从ajax请求中得到了问题。 问题是简单的文本,具有“填补差距”的地方的特定占位符。 问题可以有一个或多个“填补空白”。

这是一个例子: The apples are {green} or {red}, some times {yellow}.

这应该转换为<p>The apples are <input type='text' v-model='gap1'> or <input type='text' v-model='gap2'>, some times <input type='text' v-model='gap3'>

到目前为止,我已经设法在我的组件中使用它们具有计算值:

computed: {
    addGapsField () {
        let reg = /\{.*?\}/g
        let mtch = ''
        let text = this.question

        // loop through each match
        while((mtch = reg.exec(text)) !== null) {
            text = text.replace(mtch[0],"<input type='text'>")
        }
        return text 
    }
}

如何将v模型绑定到此动态生成输入字段。 或者还有其他方法(v-model不是我正在寻找的必要解决方案,我不太熟悉Vue.js的其他选项)。

您可以将问题拆分为一个数组并在模板内部使用v-for进行迭代(但是您需要使用<span>进行内联显示)

 new Vue({ el: "#app", data: { question: "The apples are {green} or {red}, some times {yellow}.", gaps: [], last: '' }, computed: { addGapsField () { let reg = /\\{.*?\\}/g let text = this.question.split(reg) text.forEach((part, i) => { this.gaps.push('gap' + (i+1)) }) this.last = text.pop() return text } } }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script> <div id="app"> <span v-for="(part, index) in addGapsField"> {{ part }}<input v-model="gaps[index]"> </span> <span>{{ last }}</span> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM