首页 > 编程知识 正文

Vue组件懒加载,vue动态加载组件,动态加载路由

时间:2023-05-05 03:09:47 阅读:278550 作者:1209

javascript如何动态加载模块?

python和JavaScript都是通过import去导入其他包或者模块,而我们的编译器在编译时候会直接处理import语句,所以自然就导致import最先就执行了,但是这样有个问题,如果某些模块的加载只是在特定操作下才用得到,那么如果用户打开页面就加载这些模块,造成了时间的浪费,所以有了动态加载。

if (x === 3) { import profile from './profile/Profile';}

以上代码会报错,就算不报错也会直接最先执行impory语句。
那么如何动态的加载模块呢?用import()代替import即可

const profile = () => import('./profile/Profile')

这个时候,我们定义了一个profile函数
而只有在执行profile()时,才会导入模块。
具有这样的功能的有require,意思就是在运行的时候才执行,上一篇v-bind绑定src中就用到了require

那么应用在哪呢?

import Vue from 'vue'import VueRouter from "vue-router";const Home = () => import('../views/home/Home')const Shopcart = () =>import('../views/shopcart/Shopcart')const Category = () => import('../views/category/Category')const Profile = () => import('../views/profile/Profile')

上面就使用了import(),并且是箭头函数的形式,函数名分别为Home,Shopcart,Category,Profile,而在vue的路由中,我们的路由对象是这么写的

const routes = [ { path:'', redirect: '/home', }, { path:'/home', component: Home, }, { path:'/category', component: Category, }, { path: '/home', component: Shopcart, }, { path:'/profile', component: Profile, }]

为什么component后面对应的是不带括号的函数名?
因为如果加了括号,那么就是执行函数,并返回对应的值,但不加括号就是引用,在这里是只有到对应的路由时,才会调用函数。而这个函数返回的是一个对象,为promise对象

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。