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>

Share:
10,461
Evan
Author by

Evan

... still trying to find a way to succeed

Updated on June 14, 2022

Comments

  • Evan
    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.

    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.

  • Evan
    Evan over 4 years
    so I can't use innerHtml and appendChild when using vue?
  • Andrew Vasilchuk
    Andrew Vasilchuk over 4 years
    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.
  • trusktr
    trusktr almost 3 years
    This does not answer the question.