Vue
Example of forcing component re-render
by mgoetzke
HTML
<div id="app">
<h1> Force Component Re-Render example</h1>
<br>
<mycomponent :key="id" :some-param="someval" class="comp"></mycomponent>
<br>
<button @click="rerender">
Force Re-Render
</button>
<button @click="inc">
Just change param value
</button>
<pre>The button changes a value bound to a components `key` causing a re-render</pre>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
.comp {
border: 1px solid rgba(0,100,200,0.5);
border-radius:10px;
padding: 1em;
}
Vue
new Vue({
el: "#app",
data: {
id: 1 ,
someval: 1000,
},
methods: {
rerender() {
this.id ++
},
inc() {
this.someval ++
}
},
components: {
'mycomponent': {
props: ['someParam'],
template: `
<div>
<h1>My Component</h1>
<span>{{someRandomInitialValue}}</span>
<p>
Param Value: {{someParam}}
</p>
</div>
`,
data() {
return {
someRandomInitialValue: Math.floor(Math.random()*1000)
}
},
created() {
console.log('created', this.someRandomInitialValue)
},
mounted() {
console.log('mounted', this.someRandomInitialValue)
}
}
}
})