手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >Vue.js一个文件对应一个组件实践
Vue.js一个文件对应一个组件实践
摘要:这方面官网给的示例是需要工具来编译的,但是nodejs又没有精力去学,只好曲线救国。VueJS的作者在另一个网站有一篇文章讲到可以用jQue...

这方面官网给的示例是需要工具来编译的,但是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一个文件对应一个组件实践】相关文章:

jQuery实现返回顶部功能

jQuery异步上传文件插件ajaxFileUpload详细介绍

js+html5操作sqlite数据库的方法

无刷新上传文件并返回自定义值

JQuery中上下文选择器实现方法

JQuery中DOM事件合成用法实例分析

Javascript中For In语句用法实例

多附件上传组件演示

nodejs实现遍历文件夹并统计文件大小

理解javascript中的with关键字

精品推荐
分类导航