官方文件裡的元件寫法大多需要建置工具編譯,但如果不打算投入時間學 Node.js 工具鏈,其實還有「曲線救國」的做法:用 jQuery.getScript 或 RequireJS 在執行期動態載入元件。作者當年只提到方向沒給範例,於是有了下面這套自己摸索出來的解法。
元件被拆成 js 與 html 兩個檔案,嚴格說來跟「一個檔案對應一個元件」略有出入;但當模板內容變多時,這樣拆分反而更好維護。
<h2>{{title}}</h2>
<p>{{content}}</p>
define(['text!comp.html'], function (temp) {
// 在 requirejs 中定義一個模組,依賴是模板文字
return {
props: ['title', 'content'],
template: temp
}
});
靠 text.js 外掛,模板會以純文字形式注入,直接塞給 template 就能用。
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) })
// }
// }
// });
});
<!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 與打包工具,成本也不高。