【问题标题】:How to replace a placeholders from a text with input fields and bind them with v-model with Vue.js如何用输入字段替换文本中的占位符并将它们与 v-model 和 Vue.js 绑定
【发布时间】:2018-05-21 09:47:05
【问题描述】:

我正在构建一个包含测试题的考试页面。这些问题来自“填补空白”类型。我从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-model 绑定到此动态生成的输入字段。或者有没有其他方法(v-model 不是我正在寻找的必要解决方案,我不太熟悉 Vue.js 的其他选项)。

【问题讨论】:

标签: javascript vue.js


【解决方案1】:

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

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>

【讨论】:

  • 这是一个很好的解决方案@sovalina。感谢您为构建代码 sn-p 所做的所有努力。
  • 我不得不稍微编辑一下你的代码。 splice(0,-1) 和计算属性导致了一个错误。错误在于,一旦您在输入字段中输入任何字符串,则从addGapsField 生成的数组中的最后一个元素将被删除。我添加了修复错误的实现。再次感谢您的代码。
猜你喜欢
  • 2019-05-11
  • 2019-12-06
  • 1970-01-01
  • 2017-10-26
  • 2018-05-12
  • 1970-01-01
  • 1970-01-01
  • 2019-11-22
  • 2018-08-22
相关资源
最近更新 更多