简体   繁体   中英

after changing vuejs's html heading by calling this.$refs, vuejs not updating that html element afterwards

i have simple html code:

<script src="vue.js"></script>
<div id="app1">
  <h1 ref="heading">{{ title }}</h1>
  <button v-on:click="change" ref="myButton">Change Title</button>  
</div>
<script src="app.js"></script>

and this is app.js

let v1=new Vue({
  el: '#app1',
  data: {
    title: 'The VueJS Instance'    
  },
  methods: {
    change: function() {      
      this.title ='The VueJS Instance (Updated)';      
    }
  },
  watch: {
    title: function(value) {
      alert('Title changed, new value: ' + value);
    }
  }
});

v1.$refs.heading.innerText="BEFORE Change";

As you can see i am setting innertext for "h1 heading" element. After that i am clicking on button which will call change method, after that call it opens a new dialog window saying "Title changed, new value: The VueJS Instance (Updated)" but the page (h1 heading) not updated it still remains same "BEFORE Change", What is wrong in my code, i think it should update the heading (i am using Vue.js v2.6.11 version). Thanks

You should never update the DOM of a Vue template directly - otherwise the synchronization between the virtual DOM and the real DOM will be lost and you will get all kinds of strange errors or awkward behavior.

Noone can save you from shooting yourself in the foot. Remove the last statement in your code and you will see that the title is properly updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM