(59条消息) 不使用webpack 不用编译 也能使用 vue组件,单文件vue: ,那就是使用 http
上週在 Vue 社群圈有個令人興奮的熱門新聞: CodePen 可以支援 .vue 檔案了!
Check it out - you can use `.vue` files in CodePen Projects easily:https://codepen.io/chriscoyier/project/editor/ZJYvvg/?preview_height=30&open_file=js/components/my-component.vue&preview_file=index.html
身为使用 Vue 的开发者听到这样的消息当然感到相当开心,但同时也不禁感到好奇,CodePen 是如何做到不须透过 webpack 编译 vue 档案,就可以将 .vue 的 component 如实显示到网页中。
大家都知道,在网页开发的世界中,前端是没有秘密的。 打开了开发工具,才知道原来是透过 http-vue-loader 这个工具做到的。
http-vue-loader 这套工具可提供开发者直接在网页环境中载入 .Vue File,无需透过 nodeJS 环境编译,也不需要 Build 的步骤。
用法很简单,首先在网页上载入 Vue 与 http-vue-loader,如下
<script src="https://unpkg.com/vue"></script><script src="https://unpkg.com/http-vue-loader"></script>
接著,假设我们有一个 my-component.vue 的档案:
<template><div class="hello">Hello {{who}}</div></template><script>module.exports = {data: function() {return {who: 'world'}}}</script><style>.hello {background-color: #ffe;}</style>
那麽,我们就可以在 components 内透过 httpVueLoader 来载入我们的子元件:
<div id="my-app"><my-component></my-component></div><script type="text/javascript">new Vue({el: '#my-app',components: {'my-component': httpVueLoader('my-component.vue')}});</script>
当然,httpVueLoader 也提供了类似 Vue.component('my-component', { ... }) 的宣告方式:
httpVueLoaderRegister(Vue, 'my-component.vue');new Vue({components: ['my-component'},
或是將 httpVueLoader 當作 Plugin 來使用:
Vue.use(httpVueLoader);new Vue({components: {'my-component': 'url:my-component.vue'},...
甚至是 Array 的形式也可以:
new Vue({components: ['url:my-component.vue'},...
需要注意的是,httpVueLoader 目前仅支援 Vue 2 以上的版本,而作者也在专案内说明, httpVueLoader 只是提供一个简便的测试与开发环境,方便开发者不需要透过繁複的编译过程才能使用 vue file 进行开发。若是要发佈到线上的专案,建议还是需要透过工具编译打包,会有更好的效能以及更佳的支援度喔

