vue异步组件与组件懒加载问题(import不能导入变量字符串路径)

您所在的位置:网站首页 电脑打开文件夹的快捷键是什么 vue异步组件与组件懒加载问题(import不能导入变量字符串路径)

vue异步组件与组件懒加载问题(import不能导入变量字符串路径)

#vue异步组件与组件懒加载问题(import不能导入变量字符串路径)| 来源: 网络整理| 查看: 265

vue异步组件与组件懒加载问题(import不能导入变量字符串路径) 2022年08月10日 • vue.js •我要评论 vue异步组件与组件懒加载在写项目的时候,需要动态配置路由菜单,所有的菜单都是通过配置生成的,这就意味着菜单的路径(在vue开发项目里面就是一个字符串的路径)需要异步加载进去,但是由于对webpack

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 } ] })

通过上述两种方法都能够解决 动态组件的懒加载效果

vue懒加载组件 路径不对

最近在使用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即可。 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持七九推。 

赞 (0) 打赏 微信扫一扫 微信扫一扫 相关文章: vue+vue-meta-info动态设置meta标签教程

vue+vue-meta-info动态设置meta标签教程

在写移动端项目的时候,通常都会设置meta禁止用户缩放。


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3