PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 17, 2022

[FIXED] How to replace the contents of an element?

 October 17, 2022     vue.js     No comments   

Issue

I use VueJS to set the content of elements via data defined in a Vue instance:

<p id="hello">
    {{ message }}
</p>

How can I completely replace the content of such an element (discarding the previous content, in the case above {{ message }}), to turn the <p>into for instance

<p id="hello">
     The replacement text
</p>

In jQuery I would have called $("#hello").html("the replacement text"); - what is the equivalent in VueJS?


Solution

Vue is MVVM so you map data to the view. You can replace HTML with v-html, but your html would have to be stored in your vm and this isn't recommended:

HTML:

<div id="app">
  <span v-html="message"></span>
  <button v-on:click="newHtml">Change HTML</button>
</div>

Javascript:

new Vue({
  el: "#app",
  methods: {
    newHtml() {
      this.message = '<p style="color:red;">New Message</p>';
    }
  },
  data: {
    message: "<p>Message</p>"
  }
});

Heres the JSFiddle: https://jsfiddle.net/e07tj1sa/

Really, with vue you should try to move away from thinking in jQuery, they are conceptually different. In vue the preferred method is to build up your app with reusable components not to directly affect the html in the DOM.

https://vuejs.org/guide/components.html#What-are-Components



Answered By - craig_h
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,204,463

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing