如何在组件道具中访问 Vuex 商店以设置默认值
How to access Vuex store within component props to set defaults
我是 JS 和 Vue 的新手(使用 Vue3、Vuex4、router4)。我有一个显示最近 3 个月数据的视图(带有显示其他月份的选项,因此它们需要能够更改)。
刷新此视图后,作为道具传递的那些月份消失了,您必须返回页面并再次单击link。
我将它们移至商店以进行全局访问:
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: {},
})
下面很好 - 如果缺少道具,则按预期设置默认值,因此当我的用户刷新页面或为他们的页面添加书签时,它会加载一些东西。
export default {
props: {
timeframes: {
type: Array,
default() { return ['April 2021', 'May 2021', 'June 2021'] }
}
},
但是,我需要能够弄清楚月份是什么,而不是对需要月份的每个视图进行硬编码。无法弄清楚如何让这样的东西工作:
export default {
props: {
timeframes: {
type: Array,
default() { return this.$store.state.recentMonths }
}
},
我意识到我无法访问此处的 this,只是想表明其意图。也许我把所有东西都放错了地方。有什么想法吗?
只需使用 属性 returns timeframes
或商店中的值:
组件脚本
export default {
// other stuff
computed: {
currentTimeframes: function() {
return this.timeframes || this.$store.state.recentMonths
}
}
}
我是 JS 和 Vue 的新手(使用 Vue3、Vuex4、router4)。我有一个显示最近 3 个月数据的视图(带有显示其他月份的选项,因此它们需要能够更改)。
刷新此视图后,作为道具传递的那些月份消失了,您必须返回页面并再次单击link。
我将它们移至商店以进行全局访问:
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: {},
})
下面很好 - 如果缺少道具,则按预期设置默认值,因此当我的用户刷新页面或为他们的页面添加书签时,它会加载一些东西。
export default {
props: {
timeframes: {
type: Array,
default() { return ['April 2021', 'May 2021', 'June 2021'] }
}
},
但是,我需要能够弄清楚月份是什么,而不是对需要月份的每个视图进行硬编码。无法弄清楚如何让这样的东西工作:
export default {
props: {
timeframes: {
type: Array,
default() { return this.$store.state.recentMonths }
}
},
我意识到我无法访问此处的 this,只是想表明其意图。也许我把所有东西都放错了地方。有什么想法吗?
只需使用 属性 returns timeframes
或商店中的值:
组件脚本
export default {
// other stuff
computed: {
currentTimeframes: function() {
return this.timeframes || this.$store.state.recentMonths
}
}
}