Can I declare a function inside a reactive object? #13341
Replies: 2 comments
-
That should work OK. Inside the Having the The pattern you've described, with a function inside a reactive object, is not necessarily bad if it's used in the right circumstances. Something like that is often used when coding menus or other types of interactive lists, with an array of objects representing the menu items and an But data like that can't easily be serialized as JSON due to the function. Vue itself doesn't care about that, but it can make it difficult to work with that data if it needs to be persisted somewhere, e.g. in a database or in It's also common for developers who come from an OOP background to try to apply those patterns to their reactive Vue data. While that can work in some cases, it's usually not a good fit. Putting functions inside a reactive object isn't necessarily wrong, but resist the temptation to go full-in with OOP data models. Putting functions inside reactive objects is sometimes the first step towards using classes, which can work, but there are some major caveats with it that usually aren't worth the struggle. |
Beta Was this translation helpful? Give feedback.
-
@skirtles-code thank you for your detailed answer. My use case has nothing to do with serialization, I'm exploring the ways I can keep the state for a component. But this component may appear several times in a page, so the state cannot be global. Further: this component is complex, and composed of several subcomponents. Something like:
My first try was using a composable, something like: function useDisplay() {
const name = ref('');
function change(newName: string): void {
name.value = 'ITEM ' + newName;
}
return {name, change};
}
type DisplayState = ReturnType<typeof useDisplay>;
// State manipulation:
const displayState = useDisplay();
console.log(displayState.name.value); And the children components could have: const props = defineProps<{
state: DisplayState;
}>(); But then with this idea of using a const displayState = reactive({
name: '',
setName(newName: string): void {
this.name = 'ITEM ' + newName;
},
});
type DisplayState = typeof displayState;
// State manipulation is a lot simpler:
console.log(displayState.name); So, am I thinking wrong? At the moment I'm trying to evaluate all the possible ways to do this. Do you recommend any other approaches here? |
Beta Was this translation helpful? Give feedback.
-
The following
reactive
object has a variable and also a function declared inside of it:So that I can call it directly:
The official docs say nothing about having functions inside
reactive
.Is there any problem with this approach?
Beta Was this translation helpful? Give feedback.
All reactions