本篇内容主要讲解“vue异步组件与组件懒加载问题怎么解决”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“vue异步组件与组件懒加载问题怎么解决”吧!
在写项目的时候,需要动态配置路由菜单,所有的菜单都是通过配置生成的,这就意味着菜单的路径(在vue开发项目里面就是一个字符串的路径)需要异步加载进去,但是由于对webpack的import不是很熟悉,所以就有一下的坑需要填了
_import.js
module.exports = file => () => import(file)
但是这种方法错误的原因是:
webpack 编译es6 动态引入 import() 时不能传入变量,例如dir =’path/to/my/file.js’ ; import(dir) , 而要传入字符串 import(‘path/to/my/file.js’),这是因为webpack的现在的实现方式不能实现完全动态。
可以通过字符串模板来提供部分信息给webpack;例如import(./path/${myFile}), 这样编译时会编译所有./path下的模块,但运行时确定myFile的值才会加载,从而实现懒加载。
function lazyLoadView(AsyncView) {
const AsyncHandler = () => ({
component: AsyncView,
// A component to use while the component is loading.
loading: require('@/view/system/Loading.vue').default,
// A fallback component in case the timeout is exceeded
// when loading the component.
error: require('@/view/system/Timeout.vue').default,
// Delay before showing the loading component.
// Default: 200 (milliseconds).
delay: 200,
// Time before giving up trying to load the component.
// Default: Infinity (milliseconds).
timeout: 10000
});
return Promise.resolve({
functional: true,
render(h, { data, children }) {
// Transparently pass any props or children
// to the view component.
return h(AsyncHandler, data, children);
}
});
}
const My = () => lazyLoadView(import('@/view/My.vue'));
const router = new VueRouter({
routes: [
{
path: '/my',
component: My
}
]
})
通过上述两种方法都能够解决 动态组件的懒加载效果
最近在使用VueRouter的懒加载组件的时候.
const routes = [
{
path: '/',
component: App
},
{
path: '/category',
component: resolve => {require(['./components/Category.vue'], resolve)}
}
]
但是在加载/category的时候,我发现会报错。
原来webpack会把这个懒加载单独加载一个js,默认按照
0.app.js 1.app.js ……的顺序加载的
通过简单的debug发现是0.app.js的路径不对
通过webpack的设置即可解决(我使用的laravel,配置根据情况自行修改)
Elixir.webpack.mergeConfig({
module: {
loaders: [
{
test: /\.css/,
loader: "style!css"
}
]
},
output: {
publicPath: "js/"
}
})
配置下output下的publicPath即可。
到此,相信大家对“vue异步组件与组件懒加载问题怎么解决”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。