通常vue都是搭配webpack+vue-cli使用的
如果不在nodejs环境下开发web应用呢?
这里提出一个解决方案:
1、加载requirejs,并且指定main函数
<script data-main="js/main" src="https://cdn.bootcss.com/require.js/2.3.5/require.min.js"></script>
2、定义main函数
require.config({ paths: { "text": 'https://cdn.bootcss.com/require-text/2.0.12/text.min', 'vueLoader': 'componentLoader', 'article': '../components/article', 'color': '../components/dialog/color', 'util': './common/util', 'app': './workspace/vueSet', }, waitSeconds: 3 }); require(['vueLoader', 'componentConfig', 'app'], (CptLoader, commCpt, app) => { CptLoader.config(commCpt,()=>{ setTimeout(()=>{ app.$mount(app.$el); }) }) });
可以注意到,这提供了一个CptLoader
3、组件loader源码如下所示:
/** * 组件加载器 */ //缓存Vue对象 var pool = {}; define([], () => { //根据path获取名称 function cal(path) { let r = path.split('/'); return r[r.length - 1]; } return { /** * 加载全局配置单 * @param configs */ config(configs, res){ return new Promise(() => { configs.forEach((path, index) => { require(['text!../components/' + path + '.html', '../components/' + path], (html, js) => { let v = { template: html, mixins: [ js ] }; pool[path] = v; let name = cal(path); Vue.component('v-' + name, pool[path]); if (res && index == configs.length - 1) res(); }); }); }); }, /** * 加载指定path的组件,返回Promise * @param path * @returns {function(*)} */ load(path){ return res => { let t; if (t = pool[path]) res(t); else require(['text!../components/' + path + '.html', '../components/' + path], (html, js) => { let v = { template: html, mixins: [ js ] }; pool[path] = v; res(v); }); } } }; });