Being primarily a back-end developer, the front-end side of things is still relatively new to me. I'm aware that there are concepts in this domain that I haven't fully grasped yet, and despite my efforts, I'm unable to resolve a particular issue.
In Vue (version 3), I have a component that receives an array prop from its parent. Since props are not directly mutable, I assign this prop to a const variable for manipulation. Within the setup(props) function using the composition API, I have declared this const at the beginning. In a sort function within the setup, I modify the contents of the prop by emptying it with splice and then fetching new data from the backend to push into the array.
However, this approach doesn't seem to be effective. Strangely enough, it works when I declare the const inside the sort function itself. Examples provided below:
setup(props) {
const xs: x[] = props.x;
//Called on @click event
async function toggleSortByProperty(property: string) {
const ys = await axios.dosomething();
xs.splice(0);
xs.push(...ys)
}
}
The above code snippet doesn't yield the desired outcome. Surprisingly, if I move the declaration of const xs
just below the toggleSortByProperty
line, everything seems to work magically. However, this workaround isn't ideal since I intend to use the variable in multiple functions within the setup.
Here are some additional observations:
- Upon hot-reloading (after saving changes), the functionality starts working again;
- It appears that the xs variable remains undefined for the initial click event but becomes defined thereafter, potentially causing issues.
I find myself somewhat puzzled by this situation. Any insights or suggestions would be appreciated.
Edit:
While revising this post, I attempted to address the problem concurrently and managed to identify the root cause. It was simply a lapse in judgment on my part. As it turns out, the child component was being created before 'x' was populated properly. Recently, I had replaced a v-if directive with a b-overlay (BootstrapVue) in the parent component, which merely concealed the child component instead of delaying its creation. This explains why moving the 'xs' declaration inside the toggle function resolved the issue.