I have this div that I want to pull the contents
<div id="print" ref="print_data">
<h1>{{ age }}</h1>
</div>
and tried to pull the contents using the native innerHTML
console.log( document.querySelector('#print').innerHTML );
tried also refs
console.log( this.$refs['print_data'].innerHTML );
and I can't see the content of the #print div but I can see the age content created by vue on the page. Any help, ideas please is greatly appreciated.
Here's the whole code
<div id="app">
<div id="print" ref="print_data">
<span>{{ age }}</span>
<span>{{ name }}</span>
</div>
<button @click="print">Print</button>
<button @click="print2">Print 2</button>
<button @click="print3">Print 3</button>
<button @click="print4">Print 4</button>
</div>
new Vue({
el: '#app',
data: {
age: 12,
name: ''
},
methods: {
print: function(){
this.name = 'test';
console.log(document.querySelector('#print').innerHTML);
// returns HTML but 'age' is missing, no content generated by vue
}),
print2: function(){
this.name = 'test';
console.log(this.$refs['print_data'].innerHTML);
// returns HTML but 'age' is missing, no content generated by vue
}),
print3: function(){
this.name = 'test2';
console.log(this.$refs['print_data'].content.innerHTML);
// returns error
}),
print4: function(){
this.name = 'test3';
console.log(this.$refs['print_data'].toString());
// returns [object HTMLDivElement]
}),
}
});
I found out its because vue is not finish updating the DOM resulting the issue, instead I use, the $nextTick() and wrap it with async
( async function(){
await _this.$nextTick().then(() => {
console.log(document.getElementById("print").innerHTML);
});
})()
and its working now.