2021年1月13日 星期三

vue component的強制重新render

不知道大家有沒有遇過想要重置component的時候呢,不論是在validate後想要消除紅匡,或是在某些特定場合取到資料後,需要重新繪製畫面,最直覺的作法應該是透過if消除畫面後再重新顯示吧,程式碼如下

<template>
<div v-if="show">
hello
<button type="button" @click="rerender()"></button>
</div>
</template>

<script>
export default {
data: () => ({
show: true
}),
methods: {
rerender() {
this.show = false
this.$nextTick(() => {
this.show = true
}))
}
}
}
</script>

但這樣小編總覺得不是這麼直覺跟簡潔!

那有沒有更簡單的方式呢?有的!只要利用key這個屬性讓這個component屬於一個全新的物件就可以了

<template>
<div :key="index">
hello
<button type="button" @click="rerender()"></button>
</div>
</template>

<script>
export default {
data: () => ({
index: 0
}),
methods: {
rerender() {
this.index++
}
}
}
</script>


沒有留言:

張貼留言