[Solved with rootState] How to Share Data Between Files in Vuex Store
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
A guide on how to share data between files in a Vuex store after splitting it into multiple files.
Conclusion
Using rootState
solved the issue.
getters: {
test1: (state, getters, rootState, rootGetters) => rootState.test1
}
Below is the explanation.
Wanted to Share State or Getters Between Store Files
The directory structure remains the same as before.
First, let's look at how to use state
values within a single file.
like.js
state: {
message: 'Test message!',
},
getters: {
test2: state => state.message
}
In the .vue File
<template>
<div>{{ $store.getters['like/test2'] }}</div>
</template>
<script>
import { mapGetters } from "vuex"
export default {
methods: {
...mapGetters(["like/test2"]),
},
}
</script>
This is how you write it when working within a single file.
What we want to do now is share state
or getters
data between:
like.js
⇦⇨ store.js
Using rootState Allows Data Sharing Between Files
This was really hard to find through searches.
That's why I'm writing this article.
Maybe it's just too basic for most people...
store.js
state: {
test1: 'test1',
}
like.js
getters: {
test1: (state, getters, rootState, rootGetters) => rootState.test1
}
In the .vue File
{
{
$store.getters["like/test1"]
}
}
By passing rootState
and rootGetters
as the third and fourth arguments, I was able to use global state
.
By the way, it took me three hours to figure this out. (Sigh...)
Summary
That's all.
If you have any feedback or notice any mistakes, feel free to reach out via Twitter DM. I'm happy to hear from you!