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

Unable to establish connection to MongoHQ using Node.js connection URL

I have successfully set up and run a Node.js app using my local development MongoDB with the following settings and code: var MongoDB = require('mongodb').Db; var Server = require('mongodb').Server; var dbPort = 27017; v ...

The Toggle Functionality necessitates a double-click action

I'm currently working on implementing a menu that appears when scrolling. The menu consists of two <li> elements and has toggle functionality. Everything is functioning properly, except for the fact that the toggle requires two taps to activate ...

converting code from JavaScript to Flask and then back to JavaScript, all within a single-page application

In order to make my single-page web app fully functional, I have completed the following tasks: Sent a json from .js to Flask (COMPLETED) Ran the input through a Python function called getString() and obtained a string output (COMPLET ...

What could possibly be causing the notification to fail to function in my deferred scenario?

I'm currently delving into the world of jquery deferred and making good progress, but I have encountered a hurdle when it comes to the notify feature. In my code snippet, you will notice that I attempted to use the notify method, only to find out that ...

Is it possible to use multiple AJAX requests to automatically fill out form fields?

In my Backbone.js web application, there is a form with multiple dropdowns that need to be populated with data fetched from an API. Since all the application logic resides on the client side due to using Backbone.js, I want to avoid populating these dropd ...

The spotlight is shifting towards validating a datepicker field using jQuery

I am currently working on validating a datepicker field using jQuery. However, whenever I try to validate it, the calendar popup opens up. I only want to display the validation message without the datepicker popup. ...

Utilizing Correlated Filters in Conjunction with Firebase Database

I am struggling with a firebase query that requires adding a where() condition based on a certain criteria. Specifically, I want the where() clause to be included only if certain values are entered, otherwise the basic query should run as usual. However, ...

Getting an out-of-range exception (System.ArgumentOutOfRangeException) in C# Razor pages while attempting an AJAX call

I have a razor page model that contains a get-method. public IActionResult OnGetDuration([FromBody]int id) { Subject subject = _service.GetSubjectById(id); int duration = subject.LessonsPerWeek; return new JsonResult('a&apo ...

Issue with jQuery's .height() method not updating

Here is the code I am working with: $(function() { $('#team-ch').click(function() { $('#team-camb-hert').height('auto'); }); }); I am trying to change the height of a div when a link is clicked. After adding an alert ...

Leveraging the power of node pkg to generate standalone executables while configuring npm

I have successfully used pkg to create an executable file for my node js application. Everything is working fine in that aspect. However, I am also utilizing the config module to load yaml configuration files based on the environment. During the packaging ...

Selenium javascript troubleshooting: encountering problems with splitting strings

Hello, I am new to using selenium and encountering an issue with splitting a string. <tr> <td>storeEval</td> <td>dList = '${StaffAdminEmail}'.split('@'); </td> <td>dsplit1 </td> < ...

Is it possible to utilize hooks such as 'useState' within an async/await server component?

'use client' async function Teachers (){ const response = await fetch('http://localhost:8000/teachers', }) const data = await response.json(); const [showNames , setShowNames] = useState(false); // Unable t ...

What modifications can be made to the code in order to show the upload progress for each individual file when uploading multiple files simultaneously?

I am currently working on an uploader that can handle multiple file uploads and displays the progress of each uploaded file. However, I am facing some difficulties in showing the progress of every individual file. Can anyone provide me with assistance? &l ...

Guide to Retrieving 'req' in JavaScript within Node.js / Express Framework

I have a loaded page named tournament/:key, where a Tournament object is passed. The Jade template accesses variables from the Tournament using syntax like #{tournamentData.name} to display the data on the page. The list of matches is stored as an array wi ...

Implementing basic functionality with React Router

I am currently working on implementing React router and I have a main class named App where I need to call ExpenseApp. In order for ExpenseApp to function properly, it needs to receive some 'data'. Additionally, I want ExpenseApp to be the first ...

CakePHP and Legacy Ajax Script Integration

I have an old script that I want to integrate into a cakephp application. The script uses $_POST and I'm not very experienced with this, so I need some assistance with the integration. This is what the script consists of: THE JAVASCRIPT: prototype ...

Eliminating an element from an object containing nested arrays

Greetings, I am currently working with an object structured like the following: var obj= { _id: string; name: string; loc: [{ locname: string; locId: string; locadd: [{ st: string; zip: str ...

Leveraging Polymer web components without the need for a package manager

I am looking to incorporate web components into a static web page without the need for any package manager or JavaScript build process. After referencing , I attempted to import them using unpkg by changing <script type="module" src="node_modules/@pol ...

Integrating a personalized dropdown feature into the Froala editor within an AngularJS environment

After searching for a JavaScript rich text editor that doesn't use frames and allows easy customization of the toolbar with custom dropdowns, I came across the Froala editor. It also offers AngularJS-friendly directives. Previously, I tried using Text ...

Tips for Saving process.argv in a .js File for Future Reference

I am struggling with passing process.argv value to a config file for later use. I am trying to call it from npm scripts. I have the following config file: module.exports = { foo: proccess.argv[2] } So far, I have tried calling it via node config.js &apo ...