您的位置:首页 > Web前端 > Vue.js

Vue.js一个文件对应一个组件实践

2016-10-27 14:19 841 查看

这方面官网给的示例是需要工具来编译的,但是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前端组件学习教程》,欢迎大家学习阅读。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Vue.js 组件