如何解决如何先从服务器加载对象-vuejs-vuex
因此,我想发送一个带有fetch的请求以从服务器获取一些设置。 响应必须在页面加载之前出现,并且我将这些设置保存在vuex中-这样其他所有组件都可以访问它们。
我已经能够发送请求并获取数据,但是每当我在组件中使用这些vuexed设置时,它们都不存在。这是vuex:
const state = {
settings: new Settings,is_mobile: MobileCheck(),}
这是设置请求:
class Settings {
constructor() {
this.endpoint_url = '/api/settings/'
this.image_file_path = ''
this.music_sheet_file_path = ''
this.audio_file_path = ''
this.get_settings()
}
async get_settings () {
await fetch(this.endpoint_url).then(res => res.json()).then(res => {
this.image_file_path = res.find(setting => setting.parameter === "image_file_path").value
this.audio_file_path = res.find(setting => setting.parameter === "audio_file_path").value
this.music_sheet_file_path = res.find(setting => setting.parameter === "music_sheet_file_path").value
})
.catch(err => console.log(err));
}
get_image_file_path () {
console.log(this.image_file_path)
return this.image_file_path
}
get_music_sheet_file_path () {
return this.music_sheet_file_path
}
get_audio_file_path () {
return this.audio_file_path
}
}
我将vue用作前端,将laravel用作后端。 也许我可以以某种方式将请求放入app.js文件中,或者您知道一种更好的方法。任何帮助都会很棒。
解决方法
就像@Naveen所说的,created()甚至beforeCreate()似乎都是不错的选择。
这是Vue的描述:https://vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。