When using Vue.js, pressing the enter key will automatically insert a <br> tag into the text output

I am in need of implementing basic text editor functionality into an application.
I currently have a textarea where user input is reflected in a paragraph. I have implemented event listeners for spacebar and enter key presses within the textarea to trigger specific functions.
My goal is to ensure that when the user hits the enter key, a line break is inserted in the outputted text. However, I encounter the following error:

this.textBody.appendChild is not a function

This is my current approach:

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 relevant HTML code (excerpt):

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

Answer №1

To prevent manually modifying the DOM within a Vue component, it is recommended to utilize a computed property in conjunction with v-html.

console.clear()

new Vue({
  el: "#app",
  data:{
    textBody: "Enter some text\nwith line breaks\nin this input field"
  },
  computed:{
    parsedBody(){
      return this.textBody.replace(/\n/g,"<br>")
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84f2f1e1c4b6aab0aab6">[email protected]</a>"></script>
<div id="app">
  <input v-model="textBody" size="40"></input>
  <hr>
  <p v-html="parsedBody"></p>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the trick to having the ball change colors every time it hits the wall?

Recently, I stumbled upon this interesting ball bouncing question while searching for some JavaScript code. While the basic bounce animation was simple to achieve, I started thinking about how we could make it more dynamic by changing the color of the ball ...

Improving functions in vue.js

Currently working on my personal project, which is an HTML website containing tables generated through vue.js. I believe that my code could be simplified by refactoring it, but I am unsure about where and what changes to make. Below is the section of the c ...

SCRAM-SERVER-FIRST-MESSAGE: The client's password is required to be in string format

After researching documentation from various sources on a similar issue, I have not been successful in resolving this specific error within my code. throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string') ^ ...

Eliminate spacing between divs of varying heights

I'm facing an issue with my small gallery of images. Despite having the same width, they vary in height causing the second row to start below the tallest image from the previous row. How can I eliminate these empty spaces while still maintaining the v ...

Is it possible to utilize relative paths with webpack dev server in React JS projects?

While running the development server on localhost:3000 using npm run start, everything functions as expected. I am utilizing react-scripts and have not ejected the react app. Currently, my goal is to configure the dev server behind a reverse proxy so that ...

What is the best way to ensure a component method is called every time the component is displayed in Vue2?

In Vue2, there is no built-in onShow lifecycle method available in Vue components. Is there a way to trigger a component method every time the component is displayed in vue2? ...

"Enhancing JSON elements on the fly with WSO2's enrich mediator: A step-by-step guide

I attempted to utilize the following configuration: <property name="messageType" scope="axis2" type="STRING" value="application/xml"/> <property expression="get-property('orderSourceSF')& ...

Embrace positive practices when working with nodejs

What is the best way to enhance the readability of my code by replacing the extensive use of if and else if statements when detecting different file extensions? Currently, I have over 30 else ifs in my actual code which makes it look cluttered. // Retrie ...

Preserving information throughout an online browsing session

Is there a way to save the data about which buttons a user clicked on while visiting our website without using a database? The issue is that any array I use gets reset every time the user is redirected from the page. Note: I'm still learning PHP ...

CORS Policy Blocking React and Express Access to Fetch Data from Origin

Currently, I am diving into the world of React and Express in an attempt to enable local file uploads from a React component and have Express handle the incoming files. Unfortunately, no matter what methods I try, I keep encountering this error message: A ...

Modify a property within an object stored in an array using React with Redux

When trying to dispatch an action that updates values in the redux state by passing an array, I encountered an issue. It seems that despite attempting to update the array by changing object values, I kept facing this error - "Cannot assign to read only pro ...

Guide on linking Influxdb information in a Vue application using node.js?

I have successfully connected my InfluxDB database to my Vue app and can log data in the terminal using the code below: // index.js import express from "express"; // These lines make "require" available import { createRequire ...

AngularJS $http get isn't functioning properly, but surprisingly $.ajax works perfectly

Recently delving into the world of AngularJS, I am facing a hurdle with $http functionality. In my factory setup below: app.factory('employeeFactory', function ($http) { var factory = {}; // Retrieving data from controller var emplo ...

Is it considered bad practice to have several Node.js "Apps" in a single server file?

Currently, I am managing two (soon to be three) node.js websocket apps using a single server.js file. To serve my page and a particle physics "game" that I created, I am utilizing express. Additionally, I plan on building a chatroom as a learning experienc ...

When it comes to assigning a background to a div using jQuery and JSON

I have been experimenting with creating a database using only JSON and surprisingly, it worked once I added a "js/" in the URL. However, my current issue lies with CSS. Let me elaborate. Here is the JSON data: [ { "title":"Facebook", ...

The limitation of jquery fileupload is that it does not support the selection of files with varying file

Is it possible to prevent files with certain extensions from being uploaded to my server? Specifically, using jQuery fileupload, how can I restrict the selection of multiple file types simultaneously, such as pdf and tif? ...

Retry request with an AngularJS interceptor

Currently, I am in the process of developing an Angular application and encountering some challenges while implementing a retry mechanism for the latest request within an HTTP interceptor. The interceptor is primarily used for authentication validation on ...

Clicking in Javascript can hide the scroll and smoothly take you to the top of the page

For my website, I found this useful tool: It's been working great for me, but one issue I've encountered is that when I click on a picture using the tool, its opacity changes to 0 but the link remains in the same spot. I'm trying to figure ...

Having trouble getting collision events to trigger in ThreeJS when using the PhysiJS physics engine?

When an object falls and collides with the ground, an alert box should pop up displaying the message "Box just hit the ground". However, there seems to be an issue as the alert box is not being created upon collision. Additionally, no relevant JavaScript ...

When using Rspec and Capybara, utilizing jQuery to set focus on an element may not apply the `:focus` CSS as expected

I have implemented jump links for blind and keyboard users on my website, but I've hidden them off-screen visually. When these links gain focus, they are moved into the viewport. Trying to test this behavior using RSpec and Capybara has been unsucces ...