温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在vue中利用webpack实现异步加载

发布时间:2021-04-08 17:23:04 来源:亿速云 阅读:170 作者:Leah 栏目:web开发

今天就跟大家聊聊有关怎么在vue中利用webpack实现异步加载,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

1.第一例

const Home = resolve => {
  import("@/components/home/home.vue").then( module => {
      resolve(module)
  }
}

注:(上面import的时候可以不写后缀)

export default [{
  path: '/home',
  name:'home',
  component: Home,
  meta: {
    requireAuth: true, // 添加该属性可以判断出该页面是否需要登录显示
  },
}]

2.第二例

const router = new Router({
  routes: [
    {
       path: '/home',
       component: (resolve)=> {
         require(['../components/home/home'], resolve) // 省去了在上面去import引入
       }
     }
  ]
})

3.第三例,这也是推荐的一种

// r就是resolve// 路由也是正常的写法 这种是官方推荐的写的 按模块划分懒加载 
const Home = r => require.ensure([], () => r(require('../components/home/home')), 'home');
const router = new Router({
  routes: [
    {
     path: '/home/home',
     component: Home,
     name: 'home' ,
    }
  ]
})

下面给大家介绍下vue+webpack实现异步组件加载的代码,具体代码如下所示:

HTML

<input type="button" @click="showchild" value="show"> //点击按钮后,show为真,先获取child组件,再渲染div内容 
<div id="contain" v-if="show">
  <child></child>
</div>

JS

data () {
  return {
    msg: 'Welcome to Your Vue.js App',
    show:false
  }
},
methods: {
  showchild:function(){
    this.show=true;
  }
},
components: {
  'child': function(resolve) {
    require(['./components/child.vue'], resolve);
  }
}

看完上述内容,你们对怎么在vue中利用webpack实现异步加载有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI