DIV CSS 佈局教程網

Vue.js 實踐:不靠建置工具,用 RequireJS 做到一個檔案一個元件
編輯:關於JavaScript     

官方文件裡的元件寫法大多需要建置工具編譯,但如果不打算投入時間學 Node.js 工具鏈,其實還有「曲線救國」的做法:用 jQuery.getScript 或 RequireJS 在執行期動態載入元件。作者當年只提到方向沒給範例,於是有了下面這套自己摸索出來的解法。

需要用到的工具

  • vue.js 0.12.+(需 0.12 版才有的 async component 支援)
  • require.js
  • text.js —— RequireJS 的 text plugin

檔案結構

  • index.html
  • index.js
  • comp.js(元件在這裡定義)
  • comp.html(元件的模板)

元件被拆成 js 與 html 兩個檔案,嚴格說來跟「一個檔案對應一個元件」略有出入;但當模板內容變多時,這樣拆分反而更好維護。

comp.html —— 元件模板

 <h2>{{title}}</h2>
<p>{{content}}</p>

comp.js —— 元件定義

 define(['text!comp.html'], function (temp) {
    // 在 requirejs 中定義一個模組,依賴是模板文字
    return {
        props: ['title', 'content'],
        template: temp
    }
});

靠 text.js 外掛,模板會以純文字形式注入,直接塞給 template 就能用。

index.js —— 註冊元件

 require.config({
    paths: {
        // 指定 text.js 與 vue.js 路徑,不需 .js 副檔名
        text: '../../../assets/requirejs/text',
        vue:  '../../../assets/vue/vue'
    }
});

require(['vue'], function (Vue) {
    // 註冊一個非同步元件
    Vue.component('comp', function (resolve) {
        // 因為要按需載入,require(['comp']) 必須寫在 function 裡
        require(['comp'], function (comp) {
            resolve(comp);
        })
    });

    new Vue({ el: 'body' });

    // 等價寫法:在實例的 components 選項中宣告
    // new Vue({
    //   el: 'body',
    //   components: {
    //     comp: function (resolve) {
    //       require(['comp'], function (comp) { resolve(comp) })
    //     }
    //   }
    // });
});

index.html

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<component is="comp" title="我是一個組件" content="fjkldsjfkldjsklgjks"></component>
<script data-main="index" src="../../../assets/require.js"></script>
</body>
</html>

把 <component> 那行註解掉再執行,就能看出元件到底渲染了什麼。

元件一多就該抽出註冊邏輯

每加一個元件就要寫一段幾乎一樣的 Vue.component,太囉嗦。抽成工廠函式即可:

 require.config({
    paths: {
        text: '../../../assets/requirejs/text',
        vue:  '../../../assets/vue/vue'
    }
});

function conponent(name) {
    return function (resolve, reject) {
        require([name], function (comp) {
            resolve(comp);
        })
    }
}

require(['vue'], function (Vue) {
    Vue.component('comp',  conponent('comp'));
    Vue.component('comp2', conponent('comp2'));
    new Vue({ el: 'body' });
});

這套做法的價值在於:不必引入建置流程,就能享有元件化與按需載入的紅利,很適合既有專案的漸進式改造。等到時機成熟再遷移到 SFC 與打包工具,成本也不高。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved