Vuejs how to change element content using innerHtml
Asked Answered
S

2

5

Hello there I would like to know how can I change the <h3 id="score"> innerHtml when the button is clicked.

enter image description here

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? The innerHtml of h3 with id of score must change to 12.

Sopor answered 11/8, 2019 at 9:35 Comment(0)
P
2

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>
Palish answered 11/8, 2019 at 9:39 Comment(3)
so I can't use innerHtml and appendChild when using vue?Sopor
Of course you can, but you should do it in "Vue" style, using v-show or v-if on your child, and display the child conditionally.Palish
This does not answer the question.Lounging
M
6

And just like this it's done:

let html = "<b>some text</b>"  
<div v-html="html" />
Miscreant answered 14/7, 2022 at 7:37 Comment(1)
Brilliant! And this shows once more how powerful Vue3 isDuiker
P
2

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>
Palish answered 11/8, 2019 at 9:39 Comment(3)
so I can't use innerHtml and appendChild when using vue?Sopor
Of course you can, but you should do it in "Vue" style, using v-show or v-if on your child, and display the child conditionally.Palish
This does not answer the question.Lounging

© 2022 - 2024 — McMap. All rights reserved.