我正在尝试将内容的 JSON 文件加载到我的 vuejs 应用程序中并在我的组件中访问它。我可以通过创建 API 将 json 加载到 vuex 存储中:
import Vue from 'vue';
const Http = new Vue();
export function getData() {
return Http.$http.get('./app/assets/content/en_uk.json')
.then(response => Promise.resolve(response.data))
.catch(error => Promise.reject(error));
}
和一个动作
export const getSiteContent = ({commit}) => {
api.getData().then(data => {
commit('siteContent', data);
});
};
我在主 vue 实例的创建函数上运行 getSiteContent
export default new Vue({
el: '#root',
store,
router,
created() {
getSiteContent(store);
},
render: h => h('router-view')
});
在 chrome 中使用 vue 调试工具我可以看到商店
export const state = {
isSearching: false,
searchQuery: '',
siteData: {},
filteredComponents: [],
hasResults: false,
activeComponent: null
};
使用 siteData 进行更新。
这是json的一部分:
{
"global": {
"project_name": {
"text": "Project title"
},
"search": {
"form_placeholder": {
"text": "Search..."
},
"no_results": {
"text": "Sorry no results for '{0}' was found"
},
"search_text": {
"text": "You are searching for '{0}' and there are {1} found"
}
}
}
}
当我尝试访问时
computed: {
...mapGetters(['siteData']),
mumbo () {
return this.siteData.global.project_name;
}
}
在我的组件中,{{mumbo}}
我无法读取未定义的 project_name 的属性。
我觉得这是一个时间问题,因为当我将它设置为返回 siteData.global 时它不会倒下
我不确定我是否做错了什么,或者我缺少连接以使其正常工作。