Destructuring the
props
will cause the value to lose reactivity20
21export default {
22 name: "header",
23 setup({ headerContent }) {24 return () => {
25 const visitors = ref(0);
26 visitors++;
Description
When using the setup function, it will take two arguments props
and context
. It is not recommended to use destructuring of properties.
Why should we not destructure props
in setup
function ?
props
inside of a setup
function are reactive and will be updated when new props are passed in. However, because props
are reactive, you cannot use ES6 destructuring because it will remove props reactivity.
Bad Practice
<script>
export default {
/* ✗ BAD */
setup({ count }) {
watch(() => {
console.log(count) // not going to detect changes
})
return () => {
return h('div', count) // not going to update
}
}
}
</script>
Recommended
<script>
export default {
/* ✓ GOOD */
setup(props) {
watch(() => {
console.log(props.count)
})
return () => {
return h('div', props.count)
}
}
}
</script>