gpt4 book ai didi

javascript - vue中页面刷新后如何显示加载的数据?

转载 作者:行者123 更新时间:2023-11-30 20:18:43 26 4
gpt4 key购买 nike

我有一个包含一些项目的组件,这些项目是使用 get request 从 api 加载的方法。当我点击一个项目时,我使用动态路由被重定向到它自己的页面:{ path: '/:id', component: Item } .使用 currentItem() 识别单击的项目方法:currentItem() { this.items.find(item => item.code === this.$route.params.id) }其中 item.code是我从 api 获得的属性。我的问题是,当我用当前项目刷新页面时,它不再加载了。我尝试使用 beforeCreate()在自己的组件中再次加载项目。也许我可以使用 watch根据项目更改状态?

beforeCreate() {
this.$http.get(url).then(response => {
this.items = response.body;
}
},
watch: {
'$route' (to, from) {
this.currentItem()
}
}

这是一个 demo .

最佳答案

您应该为 $route 添加 watch 以在您在页面之间导航时对 id 更改使用react。但在这种情况下,currentItem 有可能返回 null,因为您的请求将在已调用监视处理程序 后结束。

第一个解决方案是监视 Item 组件中的 items 集合,并在此监视处理程序中调用 this.currentItem()。是的,您必须像示例中那样在 Item 组件中加载 items

第二个是使用 computed 属性 currentItem 代替方法,如果可能的话:

computed: {
currentItem() {
return this.items.find(item => item.code === this.$route.params.id)
}
}

这将是响应式(Reactive)的,您不再需要 watch。但是不要忘记让 this.items 默认为空数组以避免空错误。

第三种解决方案是结合第二种使用 Vuex store 在所有组件之间共享项目集合并执行如下操作:

beforeCreate() {
// you should check in this action that items already loaded earlier as well
this.$store.dispatch('loadItems');
},
computed: {
currentItem() {
return this.items.find(item => item.code === this.$route.params.id)
},
items() {
return this.$store.state.items
}
}

商店:

state: {
items: [],
itemsLoaded: false,
}
actions: {
loadItems({state, commit}) {
// avoid unnecessary loading between navigations
if (itemsLoaded) return
Vue.http.get('some url').then(response => {
commit('setItems', response.body);
commit('itemsLoaded');
}
}
},
mutations: {
setItems: (state, items) => state.items = items
itemsLoaded: (state) => state.itemsLoaded = true
}

例如,您不需要在 Item 和 Items 组件中存储项目。

抱歉发了这么长的帖子。

关于javascript - vue中页面刷新后如何显示加载的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51684240/

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