gpt4 book ai didi

javascript - 如何先从服务器加载对象 - vuejs - vuex

转载 作者:行者123 更新时间:2023-12-01 15:41:53 25 4
gpt4 key购买 nike

所以我想用 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://v2.vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks

关于javascript - 如何先从服务器加载对象 - vuejs - vuex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63602892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com