Home > Back-end >  Custom State Management not working Vue3 - TS
Custom State Management not working Vue3 - TS

Time:12-22

Problem: I need to transfer information between two separate components. Between a main component and a another component. I have tried to create a reactive State Management as described by the Vue docs, but the value of the object is always the starting, and does not reflect changes made by the other components.

What I've tried: store.ts

const valueOriginal = ref("defaultValue");
export const store = reactive({ value: valueOriginal });

componentA.vue:

import { store } from "./store";
...

...
console.log("mounted with store object value: ", this.store.value);
this.store.value = "Modified by componentA.vue";
console.log("Modified store object value: ", this.store.value);

componentB is navigated to after componentA has changed the store value...

componentB.vue:

import { store } from "./store";
...

...
console.log("mounted with store object value: ", this.store.value); // this is the default value still

CodePudding user response:

I made a StackBlitz to show a working example. I'm not quite sure how your full code looks. Your mistake could be the usage of this but I'm not sure if you are using the Composition API. You're definition of the store itself looks fine.

I do recommend using Pinia as a store management which is maintained by the Vue core team. Using stores like you currently do could lead to security vulnerabilities when used in combination with SSR (More info).

  • Related