Reputation: 30054
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?
Upvotes: 11
Views: 34710
Reputation: 32734
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
Upvotes: 18
Reputation: 9201
There are many ways to do that.Basically you have to directly change the property into data object
https://jsbin.com/wexehasege/1/edit?html,js,output
So you can create new method that change message, and then call it after instance is created - with created() lifecycle hook.
Upvotes: 0