vue-router动态载入失败时有没有回调函数啊?
发布于 8 年前 作者 wszgxa 6721 次浏览 来自 问答

vuejs社区不活跃,在这来问问。。

8 回复

主要就是想在动态载入失败后,跳转到一个网络差的页面。

按照你的需求应该是请求超时了,这个时候应该在http interceptors上入手,例如使用vue-resource,可以这样写

import Vue from 'vue';
import VueRouter from 'vue-router';
import VueResource from 'vue-resource';

Vue.use(VueRouter);
Vue.use(VueResource);

var router = new VueRouter();
router.map({});

/**
 * Http Interceptors
 */
Vue.http.interceptors.push((request, next) => {
  next((response) => {
    if (response.status === 0) {
      router.go({path: '/timeout'});
    }
  });
});

@yuyang041060120 这是在请求接口之后就跳转。但是具体的接口有具体的判断逻辑(浮框层)。加个全局的话,从timeout跳转回去, 之前的状态(没用vuex控制的)可能就消失了。

我想问问就是单纯的页面跳转时候动态加载失败的情况下有没有回调?

@wszgxa 能说个具体的例子?

这个,跟vue应该没有什么关系了, 如果使用webpack做的代码分片,那么就看看webpack有没有这个功能,如果是自己实现的,呢回调也得自己实现了。 应该是这样,

webpack的异步加载实现,目测没有回调,

 	// This file contains only the entry chunk.
 	// The chunk loading function for additional chunks
 	__webpack_require__.e = function requireEnsure(chunkId, callback) {
 		// "0" is the signal for "already loaded"
 		if(installedChunks[chunkId] === 0)
 			return callback.call(null, __webpack_require__);

 		// an array means "currently loading".
 		if(installedChunks[chunkId] !== undefined) {
 			installedChunks[chunkId].push(callback);
 		} else {
 			// start chunk loading
 			installedChunks[chunkId] = [callback];
 			var head = document.getElementsByTagName('head')[0];
 			var script = document.createElement('script');
 			script.type = 'text/javascript';
 			script.charset = 'utf-8';
 			script.async = true;

 			script.src = __webpack_require__.p + "" + chunkId + "." + ({}[chunkId]||chunkId) + ".js";
 			head.appendChild(script);
 		}
 	};

但是,router配置可以做一下处理,达到想要的效果,比如下面这样

router.map(
    {
    '/a': {
      component: function (resolve) {
		var timer = setTimeout(function () {
		alert('XX模块加载失败')
		},3000);
		require(['./xx/xx.vue'], function (component) {
		if(timer){clearTimeout(timer);}
		resolve(component)
		})
      }
    },
    。。。
  })
回到顶部