【发布时间】:2020-07-13 04:02:43
【问题描述】:
我试图在我的组件中获取一个 getter,但它显示一个错误。这是我的代码 store.js
const store = new Vuex.Store({
state: {
config:{
themes: [],
typographies:[],
},
user: {
typography_id: 1,
theme_id: null
}
},
mutations: {
FETCH_CONFIG(state, config) {
state.config.themes = config.themes;
state.config.typographies = config.typographies;
},
FETCH_USER(state, user) {
state.user.theme_id = user.theme_id;
state.user.typography_id = user.typography_id;
},
},
actions: {
fetchConfig({commit}) {
axios.get('/api/config').then( function( response ){
commit('FETCH_CONFIG', response.data);
});
},
fetchUser({commit}) {
axios.get('/api/user').then( function( response ){
commit('FETCH_USER', response.data.data[0]);
});
},
},
getters: {
themes(state) {
return state.config.themes;
},
typographies(state) {
return state.config.typographies;
},
typography(state) {
if (state.user.theme_id == 1) {
return state.user.typography_id;
} else {
var theme = state.config.themes.filter(function (el) {
return el.id == state.user.theme_id;
});
return theme[0].typography_id;
}
},
user_theme(state) {
return state.user.theme_id;
},
}
});
在我的计算组件中,我有:
...mapGetters(['typographies', 'typography'])
这是我得到的错误:
我想我做错了什么,但我不知道是什么。
【问题讨论】:
-
看起来
filter不匹配任何内容,所以theme[0]是undefined。 -
是的,但是如果我创建一个 console.log(theme[0].typography_id) 它似乎可以工作,但我得到了错误。
-
我建议在
typographygetter 中添加更多日志记录,以准确跟踪它在代码中遵循的路径。例如,尝试记录theme[0]。我怀疑 getter 被多次调用,而您只会在成功的情况下看到日志记录。debugger语句也是进一步调试的好方法。 -
能否分享一下console.log(theme[0].typography_id)的截图
-
var theme = state.config.themes.filter(function (el) { if( el.id == state.user.theme_id) { return { typography_id: el } } });这可能有效