Vue 3 sync watcher fun
by skirtle
HTML
<script src="https://unpkg.com/[email protected]/dist/vue.global.js"></script>
<div id="app">
<button @click="onClick">Change</button>
<child-component v-bind="options[optionsIndex]"></child-component>
</div>
JavaScript
const ChildComponent = {
props: ['type', 'id'],
render () {
console.log('rendering child')
return Vue.h('div', `${this.type} - ${this.id}`)
},
computed: {
path () {
return this.type + '/' + this.id
}
},
updated () {
console.log('updated')
},
watch: {
path: {
flush: 'sync',
handler () {
console.log(`path: ${this.path}`)
}
}
}
}
const app = Vue.createApp({
components: {
ChildComponent
},
data () {
const options = [
{ type: 'user', id: 40 },
{ type: 'product', id: 71 }
]
return {
options,
optionsIndex: 0
}
},
methods: {
onClick () {
this.optionsIndex = 1 - this.optionsIndex
}
}
})
app.mount('#app')