Search code examples
javascriptvue.jsvuejs2appendchild

In Vue.js, when the enter key is pressed, add a <br> tag to the text output


I need to add some basic text editor functionality to an app.
I have a textarea that when the user types something, the text is outputted in a paragraph. I am listening for spacebar and enter key presses on that textarea to trigger methods.
I want the text output to also have a line break when the enter key is pressed in the textarea but I get

this.textBody.appendChild is not a function

This is what I'm trying:

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);
    }
  }
})

The corresponding html (partly):

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

Solution

  • I would avoid manually updating the DOM yourself inside a Vue. Instead, use a computed property combined with 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>