Vuejs how to change element content using innerHtml
10,461
You should not manipulate DOM directly when using Vue.js. First off define score
data property. Vue knows when you change score
and will make DOM manipulations to update the view.
new Vue({
el: "#scoreboard",
data() {
return {
header_my: "Hello Wolrd",
score: 0
};
},
methods: {
changeScore() {
this.score = 12;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="scoreboard">
<button @click="changeScore">Change</button>
<h3>{{ score }}</h3>
</div>
Comments
-
Evan almost 2 years
Hello there I would like to know how can I change the
<h3 id="score">
innerHtml
when the button is clicked.In Vanilla Javascript I can access the element with:
const score = document.querySelector('#score');
and change it by doing this:
score.innerHtml = "13";
something like that.
<template> <div id="scoreboard"> <h4>{{header_my}}</h4> <button v-on:click="changeH3()">Change</button> <h3 id="score">0</h3> </div> </template> <script> export default { name: "scoreboard", data() { return { header_my: "Hello Wolrd" }; }, methods: { changeH3() { const h3 = document.querySelector("#score"); h3.innerHtml = "12"; } } }; </script>
How can I do this, when
changeH3
is called? TheinnerHtml
ofh3
withid
ofscore
must change to12
. -
Evan over 4 yearsso I can't use innerHtml and appendChild when using vue?
-
Andrew Vasilchuk over 4 yearsOf course you can, but you should do it in "Vue" style, using
v-show
orv-if
on your child, and display the child conditionally. -
trusktr almost 3 yearsThis does not answer the question.