這方面官網給的示例是需要工具來編譯的,但是nodejs又沒有精力去學,只好曲線救國。VueJS的作者在另一個網站有一篇文章講到可以用jQuery.getScript或RequireJS實現組件,卻沒有給示例,於是自己摸索出了一種方法。
用到的工具:
vue.js --- 0.12.+ (需要0.12中async component支持)
require.js
text.js --- RequireJS text plugin https://github.com/requirejs/text
文件列表
index.html
index.js
comp.js (組件在這裡定義)
comp.html (組件的模板)
實際上組件分成了js和html,html是模板內容,這裡似乎與“一個文件對應一個組件”稍有不符,但如果模板內容比較多,這是有必要的,也更便於維護。 直接上代碼。
comp.html -- 組件模板
<h2>{{title}}</h2>
<p>{{content}}</p>
comp.js -- 組件定義
define(['text!comp.html'], function (temp) { // 在requirejs中定義一個模塊,依賴為模板文本
return {
props: ['title', 'content'],
template: temp
}
});
至此,一個簡單的模板就建好了。然後就是在VueJS中注冊這個組件。
index.js
require.config({
paths: { // 指定text.js和vue.js的路徑,不需要.js後綴,詳見RequireJS文檔
text: '../../../assets/requirejs/text',
vue: '../../../assets/vue/vue'
}
});
require(['vue'], function (Vue) { // 依賴vue.js
Vue.component('comp', function (resolve) { // 注冊一個異步組件
require(['comp'], function (comp) { // 因為我們要按需加載組件,因此require(['comp'])必須在function裡
resolve(comp)
})
});
new Vue({
el: 'body'
});
//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>注釋掉就能看到區別。
如果組件比較多,注冊組件就會很繁瑣,因此可以把這部分提煉出來。
改進後的index.js
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'
});
});
至此。
本文已被整理到了《Vue.js前端組件學習教程》,歡迎大家學習閱讀。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。