In my Vue.js 3 application, I have several single file components and I am looking for a simple way to manage global state. The documentation on state management is helpful, but it mainly focuses on using a reactive object returned from the data function within the same file. My challenge lies in implementing a shared store across multiple files.
- app.vue
- component-a.vue
- component-b.vue
- store.js
Let's take a look at these files:
app.vue
<template>
<div>
<div>How much money do you have?</div>
<input type="number" v-model="currentAmount" />
<br />
<div>How much money do you want?</div>
<input type="number" v-model="desiredAmount" />
</div>
</template>
<script>
import ComponentA from './component-a.vue';
import ComponentB from './component-b.vue';
export default {
components: {
ComponentA,
ComponentB
},
data() {
return {
currentAmount: 0,
desiredAmount: 0
}
},
}
</script>
component-a.vue
<template>
<div>
<div>You have {{ remainingAmount }} to reach your goal.</div>
</div>
</template>
<script>
export default {
data() {
return {
remainingAmount: 0
}
},
}
</script>
component-b.vue
<template>
<div>
<div>You are {{ progress }}% of the way there!</div>
<button @click="increaseGoal">increase goal by $10</button>
</div>
</template>
<script>
export default {
data() {
return {
progress: 0
}
},
methods: {
increaseGoal() {
// need to increase targetAmount by $10
store.targetAmount += 10;
}
}
}
</script>
store.js
import { reactive} from 'vue';
const store = reactive({
startingAmount: 0,
targetAmount: 0
});
Although the UI renders fine, the data is not being shared between the components. There seems to be a disconnect between the store and the three .vue files. I'm unsure how to properly link the store.js with the components.
If you have any insights on how to connect a shared store with multiple single file components without using Vuex, I would appreciate your guidance.