iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >vue异步组件与组件懒加载问题(import不能导入变量字符串路径)
  • 107
分享到

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

2024-04-02 19:04:59 107人浏览 安东尼
摘要

目录Vue异步组件与组件懒加载错误的原因分析解决方案一解决方案二vue懒加载组件 路径不对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
    }
  ]
})

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

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即可。 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。 

--结束END--

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

本文链接: https://www.lsjlt.com/news/144701.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作