简体   繁体   中英

Custom State Management not working Vue3 - TS

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

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM