Vue.js "一个文件对应一个组件"的实现方式

这方面官网给的示例是需要工具来编译的,但是nodejs又没有精力去学,只好曲线救国。VueJS的作者在另一个网站有一篇文章讲到可以用jQuery.getScript或RequireJS实现组件,却没有给示例,于是自己摸索出了一种方法。

用到的工具:

文件列表

  • 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'
    });
});

至此。

转载于:https://my.oschina.net/u/580483/blog/477473

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值