Yes! You can define a function inside a reactive
object, Vue reactive is a proxy
that tracks property access and updates, so whenever you update the names
array, the change will be accessible.
Be careful with this
keyword, with normal functions add() {...}
dynamically bind this
to the reactive object, but arrow functions add: () => {...}
do not have their own this
, for more details about this
see https://stackoverflow.com/a/134149/29157031
Here is an example:
<script setup lang="ts">
import { reactive } from 'vue'
const state = reactive({
names: [] as string[],
add(name: string): void {
this.names.push(name);
},
add_2: (name: string): void => {
// this.names.push(name); // ERROR: Cannot read properties of undefined (reading 'names')
state.names.push(name);
},
});
setTimeout(()=>{
state.add('1');
state.add_2('2');
}, 2000)
</script>
<template>
<button @click="()=>state.add('John')">Add Name 1</button>
<button @click="()=>state.add_2('John')">Add Name 2</button>
<p>Names: {{ state.names }}</p>
<p>Count: {{ state.names.length }}</p>
</template>
see this vue playground to test the code