How can I efficiently clean up props in Vue 3 before using them?
I am faced with the challenge of handling props that can be either objects or stringified JSON versions of those objects. Currently, the application I'm working on tackles this issue by modifying the props in the created method.
However, this approach is not ideal as it triggers warnings from my linter. Since I cannot control the components using my component beforehand, I cannot fix this in the parent before my component is utilized.
After exploring the possibility of utilizing a default option with a method to handle rawData, I attempted the following:
defineProps({
data: {
type: [Object, String],
default: ((rawData) => {
if(typeof rawData === 'string') {
return JSON.parse(rawData);
}
return rawData;
}
}
});
Unfortunately, this did not produce the desired outcome. It appears that the default value is only applied when no data is provided, which is expected behavior. Is there a way to achieve this transformation every time, even when data is supplied?
As an alternative solution, I could store the props in refs and then modify them accordingly. However, since I do not require the values to be reactive, this might seem excessive.