In Vue.js, utilize a contenteditable div to dynamically add an HTML element and bind it with v-model

Below is the HTML code I have written.

<div id="app">

  <button @click="renderHtml">Click to append html</button>
  <div class="flex">
      <div class="message" @input="fakeVmodel" v-html="html" contenteditable="true"></div>
      <div class="message">{{ html }}</div>
  </div>
</div>

Here is the JavaScript part

let app = new Vue({
    el: '#app',
    data: {
        html: 'some text',
    },
    methods: {
        fakeVmodel: function(e){
            this.html = e.target.innerText;
        },
        renderHtml: function(){
          this.html += '<img src="https://cdn-images-1.medium.com/max/853/1*FH12a2fX61aHOn39pff9vA.jpeg" alt="" width=200px>';
        }
    }
});

The issue arises when I click the button to add an HTML tag (img) to my variable (html), it works. However, after typing, it removes the inserted tag part. Is there a way to successfully append HTML code in Vue?

Check out the CodePen example provided here

Answer №1

The primary issue: The issue lies in the html disappearing due to the line this.html = e.target.innerText;. To resolve this, replace it with this.html = e.target.innerHTML;. The use of innerHTML ensures that the full HTML content is captured.

Secondary concern: Another problem occurs after typing where the cursor jumps to the start of the div. This behavior is caused by v-html triggering updates to the div.

To address this, implement a solution where v-html only triggers updates on focusout.

Complete Sample

let app = new Vue({
  el: '#app',
  data: {
    html: 'some text',
  },
  methods: {
    updateHtml: function(e) {
      this.html = e.target.innerHTML;
    },
    renderHtml: function(){
      this.html += '<img src="https://cdn-images-1.medium.com/max/853/1*FH12a2fX61aHOn39pff9vA.jpeg" alt="" width=200px>';
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.js"></script>
<div id="app">
 
  <button @click="renderHtml">click to append html</button>
  <div class="flex">
      <div class="message" @focusout="updateHtml" v-html="html" contenteditable="true"></div>
      <br>
      <div class="message">{{ html }}</div>
  </div>
</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

Can the height of one div be determined by the height of another div?

Here's the specific situation I am facing: I want the height of Div2 to adjust based on the content of Div3, and the height of Div3 to adapt based on the content in Div2. The height of Div1 is fixed at 500px. Some of the questions that arise are: I ...

What is causing this setInterval function to run repeatedly?

Below is the code snippet from my Vue application: mounted: function () { this.timer = setInterval(async () => { if (this.progress >= 1) { this.progress = 1 clearInterval(this.timer) } console.log('update& ...

script to pause video using jQuery

I have a script that works perfectly, but currently it only stops an instance of a playing video if a new video is started. I want to modify the script so that ALL instances of playing videos are stopped when the function stopAllButMe(); is called. Can s ...

Prevent scrolling within input field

I have a text entry field with background images that separate each letter into its own box. Unfortunately, an issue arises when I reach the end of the input: the view automatically scrolls down because the cursor is positioned after the last letter enter ...

Adjust the size of the plane in Three.js to match the entire view

English is not my strong suit, as I am Japanese. I apologize for any confusion. Currently, my focus is on studying Three.js. I aim to position a Plane directly in front of the camera as the background. My goal is to have the Plane background fill the en ...

Is it possible to implement a setInterval on the socket.io function within the componentDidMount or componentDidUpdate methods

I'm currently working on a website where I display the number of online users. However, I've encountered an issue with the online user counter not refreshing automatically. When I open the site in a new tab, the counter increases in the new tab b ...

Calculate the product of a JavaScript variable and a PHP variable, then show the result on the

I need to calculate the product of a PHP variable value and a JavaScript variable, then show the result on the screen. Here is my PHP code: <?php require 'config.php'; session_start(); ?> <html> <head> < ...

Sending an AJAX request to a Symfony controller's URL

Recently, I encountered an issue with integrating a piece of code from backend.php into my Symfony controller. In the initial setup, I had an AJAX call in a JS file that interacted with backend.php to test some functionality. function postRequest() { var ...

I need to press the button two times to successfully submit

I am experiencing a remote validation issue. When I click on the submit button without focusing on the text box, it triggers a remote ajax call for validation. However, when I press the submit button a second time, the form gets submitted. On the same cl ...

Error: $this.text is throwing a TypeError and is not working as a function

Upon examining the code below: var $this = $(this).children('div.submenu1').children('a.subtile')[0], title = $this.text(), name = $this.attr('node').val; An error is encountered: Uncaught TypeError: $this.text is not a fun ...

Change Node.js version to 6.11.5 on a Windows system

My current node version is v8.2.1, but Google Cloud Functions only supports v6.11.5. I need to switch my node version accordingly and preferably do it using npm. How can I achieve this? I have explored How to change to an older version of node.js for guid ...

Order an array in Javascript based on the day of the month

I am trying to create a unique function that changes the order of a string based on the day of the month. For instance, if the input string is "HELLO" and today's date is the 1st of April, the output should be "LHEOL". On the 2nd of April, it should ...

Refresh an Angular page automatically

Having a small issue in my angular application. The problem arises on the first page where I display a table listing all employees along with a "Create New Employee" button that opens a form for adding a new employee. However, after submitting the form and ...

Converting JSON formatting from Object to Array: A Comprehensive Guide

Encountering another issue with changing the JSON array output. Struggling to figure out why it's not rendering the other files. Providing a clearer explanation below: In my code snippet, when I use data[name] = {, each return name is rendered into ...

Implementing the use of a partial view in ASP.NET MVC with the help of JavaScript

I am faced with a challenge of displaying 15 different partial views based on the user's selection from a menu tab. Essentially, I have these 15 menu tabs on one side of the page, and when a user clicks on a tab, the content related to that tab should ...

What is the best way to add an array of JSON objects to another array of JSON objects?

The current JSON array obtained from the response is as follows: comments:[{id: "3124fac5-9d3e-4fa9-8a80-10f626fbf141", createdDate: 1469606019000,…},…] 0:{id: "3124fac5-9d3e-4fa9-8a80-10f626fbf141", createdDate: 1469606019000,…} createdBy:{id: "cf2 ...

Issue with CSS styles not linking correctly to ejs templates

I'm having trouble linking my CSS stylesheet in my project. I have the CSS file stored in a public folder with a css subfolder within it. Despite trying various methods, I can't seem to get the stylesheet to connect properly. Below is a snippet f ...

Automatically fill in Vue files

Is there a quick way in Vue to automatically populate an empty file with the template, script, and style tags along with default content? For example, in VS Code you can use the shortcut ! + Enter to insert all necessary HTML tags/codes. I'm wonderin ...

Debounce fails to honor the specified timeout period

I'm currently working on implementing a debounce function to handle an HTTP request function. The code is very similar to the example provided below, with only minor changes in function names. To start off, here's the debounce function I am usin ...

Incorporating a transparent icon onto an HTML background

I'm struggling to place a transparent white envelope icon on a green background. I don't understand why it's not working, especially when the telephone icon worked fine. Side Question.: Any recommendations for how to add something above the ...