Vue.js一个文件对应一个组件实践
2019/6/27 21:40:59
本文主要是介绍Vue.js一个文件对应一个组件实践,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
这方面官网给的示例是需要工具来编译的,但是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一个文件对应一个组件实践的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-30React Native常用组件-点击组件
- 2024-05-30uniapp+vue3+uv-ui手机端后台OA管理模板
- 2024-05-29Python网络爬虫的时候json=就是让你少写个json.dumps()
- 2024-05-27React Native常用组件-展示组件
- 2024-05-27React Native常用组件-列表组件
- 2024-05-09vue3开发前端表单缓存自定义指令,移动端h5必备插件
- 2024-05-09React Hooks在class组件中的使用方式
- 2024-03-30[OIDC in Action] 2. 基于OIDC(OpenID Connect)的SSO(纯JS客户端)
- 2024-03-29terraform jsonencode
- 2024-03-13vuex-persist