vue.js 異步組件

使用時才裝入須要的組件,能夠有效的提升首次裝入頁面的速度。好比在路由切換時html

異步組件的實現

Vue.js容許將組件定義爲一個工廠函數,動態地解析組件的定義。工廠函數接收一個resolve回調,成功獲取組件定義時調用。也能夠調用reject(reason)指示失敗。vue

假設咱們有兩個組件Home、About。Home組件和首頁同步加載,而About組件則按需加載。案例的代碼有首頁index.html,組件代碼about.js構成。node

首先是about.js代碼:webpack

Vue.component('about', {
  template: '<div>About page</div>'
});

接下來是index.html代碼:git

<html>
<head>
  <title>Async Component test</title>
</head>
<body>

  <div id="app">
    <router-link to="/home">/home</router-link>
    <router-link to="/about">/about</router-link>
    <router-view></router-view>
  </div>

  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
  <script>
    function load(componentName, path) {
      return new Promise(function(resolve, reject) {
        var script = document.createElement('script');
        script.src = path;
        script.async = true;
        script.onload = function() {
          var component = Vue.component(componentName);
          if (component) {
            resolve(component);
          } else {
            reject();
          }
        };
        script.onerror = reject;
        document.body.appendChild(script);
      });
    }
    var router = new VueRouter({
      routes: [
        {
          path: '/',
          redirect:'/home'
        },
        {
          path: '/home',
          component: {
            template: '<div>Home page</div>'
          },
        },
        {
          path: '/about',
          component: function(resolve, reject) {
            load('about', 'about.js').then(resolve, reject);
          }
        }
      ]
    });
    var app = new Vue({
      el: '#app',
      router: router,
    });
  </script>

</body>
</html>

爲了加載在服務器的js文件,咱們須要一個HTTP服務器。可使用node.js的http-server實現。安裝並啓動一個服務器的方法:web

npm install http-server -g
http-server

訪問:vue-router

http://127.0.0.1:8080

咱們便可在首頁看到home和about的連接,點擊home能夠顯示home組件,點擊about,若是尚未加載過,就加載about組件。npm

對index.html內的代碼稍做解釋:bootstrap

  1. 組件定義爲function(resolve, reject) {}函數,其內調用load函數,成功後resolve,不然reject服務器

  2. 函數load內經過建立標籤script加載指定文件,並經過onload事件當加載完成後,經過Vue.component驗證組件,存在就resolve,不然reject

異步組件的webpack方案

若是使用webpack腳手架的方式,加載異步組件將會更加直觀。本節會用一樣的案例,使用webpack作一次演示。

首先建立腳手架,並安裝依賴

vue init webpack vuetest
cd vuetest
npm i
npm run dev

訪問localhost:8080,能夠看到Vue的默認頁面。而後替換main.js文件爲:

import Vue from 'vue'
import App from './App'

import VueRouter from 'vue-router'
import About from './components/about'
Vue.use(VueRouter)

const Home = { template: '<div>home page</div>' }
// const About = { template: '<div>about page</div>' }
const router = new VueRouter({
  routes :[
    { path: '/home', component: Home },
    { path: '/about', component: function (resolve) {
        require(['./components/about'], resolve)
        } 
    },
    { path: '/', redirect: '/home' }
  ]
})
new Vue({
  el: '#app',
  template: '<App/>',
  router: router,
  components: { App }
})

並添加組件about到src/components/about.vue:

<template>
  <div>about page</div>
</template>

再次訪問localhost:8080,能夠看到Home組件和about組件的連接,點擊連接試試,能夠看到組件home和about都是能夠加載的。

這裏特別要解釋的是代碼:

component: function (resolve) {
    require(['./components/about'], resolve)
    } 
}

Vue.js支持component定義爲一個函數:function (resolve) {},在函數內,可使用相似node.js的庫引入模式

require(['./components/about'], resolve)

從而大大的簡化了異步組件的開發。固然,代價是你須要使用腳手架代碼。這個特殊的require語法告訴webpack自動將編譯後的代碼分割成不一樣的塊,這些塊將經過按需自動下載。

關於

做者:劉傳君

建立過產品,創過業。好讀書,求甚解。
能夠經過 1000copy#gmail.com 聯繫到我

出品

bootstrap小書 https://www.gitbook.com/book/...
http小書 http://www.ituring.com.cn/boo...
Git小書 http://www.ituring.com.cn/boo...

相關文章
相關標籤/搜索