Reputation: 3158
I have this .ts file:
import { reactive, toRefs } from 'vue'
export const TitleComponent = () => {
const obj = reactive({
title: "This should be reactive"
})
const updateObj = () => {
obj.title = 'This is now different'
}
return {...toRefs(obj), updateObj }
}
I then import is into a vue component which DISPLAYS it
<template>
<h1>{{ title }}</h1>
</template>
import { defineComponent } from 'vue'
import { TitleComponent } from 'some/place'
export default defineComponent({
const { title } = TitleComponent()
return { title }
})
Then, I use the function updateObj
in another component that runs that method. But it doesn't update the title value. What gives?
<template>
<button @click="updateObj">Click Me</button>
</template>
import { defineComponent } from 'vue'
import { TitleComponent } from 'some/place'
export default defineComponent({
const { updateObj } = TitleComponent()
return { updateObj}
})
Upvotes: 2
Views: 569
Reputation: 1544
Move obj
outside of export const TitleComponent = () => {}
.
import { reactive, toRefs } from 'vue';
const obj = reactive({
title: 'This should be reactive'
});
export const TitleComponent = () => {
const updateObj = () => {
obj.title = 'This is now different'
};
return { ...toRefs(obj), updateObj };
}
When its inside and you import/call TitleComponent()
it creates a new instance of obj
every time.
Upvotes: 5