Reputation: 37
I'm new to JS and Vue (using Vue3, Vuex4, router4). I have a view that displays data for the 3 most recent months (with options to show other months, so they need to be able to change).
When this view is refreshed, those months that were passed as props are gone, and you have to go back a page and click the link again.
I moved them to the store to have global access:
import { createStore } from 'vuex'
export default createStore({
state: {
isLoading: false,
recentMonths: []
},
mutations: {
setIsLoading(state, status) {
state.isLoading = status
},
},
actions: {
// eslint-disable-next-line no-unused-vars
setRecentMonths({ commit }, payload) {
const tfs = new Array()
for (let m of Array(payload.numToGet).keys()) {
let curDate = new Date()
let prvDate = new Date(curDate.getFullYear(),curDate.getMonth() - m, curDate.getMonth())
tfs.push(prvDate.toLocaleString('en-US', {month: 'long', year: 'numeric'}))
}
this.state.recentMonths = tfs.reverse()
}
},
modules: {},
})
Below is fine - sets the default as expected if the props are missing, so when my users refresh or bookmark their page, it will load something.
export default {
props: {
timeframes: {
type: Array,
default() { return ['April 2021', 'May 2021', 'June 2021'] }
}
},
But, I need to be able to figure out what the months are, rather than hard-coding for each view that requires the months. Cannot figure out how to get something like this to work:
export default {
props: {
timeframes: {
type: Array,
default() { return this.$store.state.recentMonths }
}
},
I realize I have no access to this here, just trying to show what the intention is. Perhaps I'm putting everything in the wrong place. Any ideas?
Upvotes: 0
Views: 1484
Reputation: 5118
Just use a computed property that returns timeframes
or the value from the store:
Component script
export default {
// other stuff
computed: {
currentTimeframes: function() {
return this.timeframes || this.$store.state.recentMonths
}
}
}
Upvotes: 2