As I work with the Vue composition API in one of my components, I encountered an issue where a component doesn't display the correct rendered value when a computed property changes. Strangely, when I directly pass the prop to the component's render, it works fine, but not when I go through a computed property.
I find this behavior surprising because I expected the computed property to be reactive as well. Can anyone shed light on why this might be happening?
Below is the snippet of code in question:
App.vue
<template>
<div id="app">
<Tester :testNumber="testNumber" />
</div>
</template>
<script>
import Tester from "./components/Tester";
export default {
name: "App",
components: {
Tester,
},
data() {
return {
testNumber: 1,
};
},
mounted() {
setTimeout(() => {
this.testNumber = 2;
}, 2000);
},
};
</script>
Tester.vue
<template>
<div>
<p>Here is the number directly from the props: {{ testNumber }}</p>
<p>
Here is the number after passing through computed (doesn't update):
{{ testNumberComputed }}
</p>
</div>
</template>
<script>
import { computed } from "@vue/composition-api";
export default {
props: {
testNumber: {
type: Number,
required: true,
},
},
setup({ testNumber }) {
return {
testNumberComputed: computed(() => {
return testNumber;
}),
};
},
};
</script>
If you're interested, you can access a working codesandbox here.
While I do understand that using a watcher could solve this, I prefer to explore cleaner alternatives to address this challenge.