javascript - 在 Vue.js 中,当按下回车键时,向文本输出添加一个 <br> 标签

标签 javascript vue.js vuejs2 appendchild

我需要向应用添加一些基本的文本编辑器功能。
我有一个文本区域,当用户输入内容时,文本会输出到一个段落中。我正在监听空格键并在该文本区域上输入按键以触发方法。
当在文本区域中按下回车键时,我希望文本输出也有一个换行符,但我得到了

this.textBody.appendChild is not a function

这就是我正在尝试的:

new Vue({
  el: "#app",
  data: {
    title: "",
    textBody: ""
  },
  methods: {
    logSpacebar: function(){
      console.log("spacebar pressed");
      //Fire corrector API?
    },
    logEnter: function(){
      console.log("pressed enter");
      var breakTag = document.createElement("br");
      this.textBody.appendChild(breakTag);
    }
  }
})

对应的html(部分):

<input type="text" v-model="title"/>
<textarea name="" cols="30" rows="10" v-model="textBody" v-on:keyup.space="logSpacebar" v-on:keyup.enter="logEnter"></textarea>
<h2>Title: {{title}}</h2>
<p>Text body: {{textBody}}</p>

最佳答案

我会避免在 Vue 中自己手动更新 DOM。相反,使用计算属性结合 v-html

console.clear()

new Vue({
  el: "#app",
  data:{
    textBody: "type some text\nwith returns interspersed\nin this textarea"
  },
  computed:{
    parsedBody(){
      return this.textBody.replace(/\n/g,"<br>")
    }
  }
})
<script src="https://unpkg.com/vue@2.4.2"></script>
<div id="app">
  <textarea v-model="textBody" cols="80" rows="10"></textarea>
  <hr>
  <p v-html="parsedBody"></p>
</div>

关于javascript - 在 Vue.js 中,当按下回车键时,向文本输出添加一个 <br> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47103864/

相关文章:

javascript - Vue-resource 无法加载 express 静态文件

vue.js - 如果在 vue 中使用数组作为模型,如何获取复选框的选中值

javascript - 如何在每个页面部分突出显示链接?

javascript - Node.js 更改静态文件的路径

javascript - webkit 浏览器中 svg 文本的奇怪行为

javascript - VueJS。切换子组件模态

javascript - Vuejs 运行 "npm run build"随机工作

javascript - 如何根据文本长度使文本最适合?

javascript - 在blade中定义vuejs组件

vue.js - 如何在 Vuejs 渲染函数中复制插槽?