首頁  >  文章  >  web前端  >  vue+webpack非同步載入方法總結

vue+webpack非同步載入方法總結

php中世界最好的语言
php中世界最好的语言原創
2018-04-27 09:30:301890瀏覽

這次帶給大家vue webpack非同步載入方法總結,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组件,再渲染p内容 
<p id="contain" v-if="show">
  <child></child>
</p>

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

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

vue router讓子路由全部分離為獨立元件

vue.js前後端資料交互步驟詳解

以上是vue+webpack非同步載入方法總結的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn