首页 > 语言 > JavaScript > 正文

vue+webpack实现异步加载三种用法示例详解

2024-05-06 15:19:43
字体:
来源:转载
供稿:网友

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不要忽略。这个例子应该比较直观了。点击按钮之后改变了变量show的布尔值为真,由于child.vue是异步组件,所以会先ajax获取组件然后渲染。

总结

以上所述是小编给大家介绍的vue+webpack实现异步加载三种用法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对错新站长站网站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选