【发布时间】:2020-04-09 23:03:00
【问题描述】:
我制作了一个 vue SPA,当我转到新路由时,页面将在我对服务器的请求完成之前加载,这意味着在数据显示之前会有 0.5 秒左右的延迟。我想添加一个诸如 NProgress 之类的加载器,它仅在请求完成后才进入页面,并且所有内容都已加载,因此数据将立即出现,而不是我的元素为空,然后延迟后出现数据。
我该怎么做?
谢谢
【问题讨论】:
标签: api vue.js routes axios loader
我制作了一个 vue SPA,当我转到新路由时,页面将在我对服务器的请求完成之前加载,这意味着在数据显示之前会有 0.5 秒左右的延迟。我想添加一个诸如 NProgress 之类的加载器,它仅在请求完成后才进入页面,并且所有内容都已加载,因此数据将立即出现,而不是我的元素为空,然后延迟后出现数据。
我该怎么做?
谢谢
【问题讨论】:
标签: api vue.js routes axios loader
您可以使用 isLoading 布尔值在为 true 时有条件地渲染进度条,如果为 false 则渲染组件的其余部分。
我看到你提到了 axios。不太可能,但是如果您在初始页面加载后不再进行任何 API 调用,您可以在您的 axios 实例中创建拦截器,在请求开始时将一段 vuex 状态设置为 true,在请求完成时设置为 false。然后你可以有条件地在 App.vue 中呈现你的进度条,当为真时,你的路由器视图为假。
import axios from 'axios'
import store from '@/store'
const api = axios.create({
baseURL: 'URL',
})
api.interceptors.request.use(config => {
store.commit('changeLoadingStatus', true)
return config
}, error => {
// Handle errors
})
api.interceptors.response.use(response => {
store.commit('changeLoadingStatus', false)
return response
}, error => {
// Handle errors
})
export default api
【讨论】:
我自己没有试过,但也许你可以试试这样的东西
const router = new Router({
routes: [
{ path: '/', name: 'home', component: Home },
{ path: '/about', name: 'about', component: About }
]
})
router.beforeResolve((to, from, next) => {
// If this isn't an initial page load.
if (to.name) {
// Start the route progress bar.
NProgress.start()
}
next()
})
router.afterEach((to, from) => {
// Complete the animation of the route progress bar.
NProgress.done()
})
【讨论】: