通常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); }); } } }; });
它提供了两个函数:
a、config,用于加载一个数组作为配置单,该数组内的字符串都会被当作vue全局组件加载
b、load,加载单个vue组件
需要注意的是,它默认组件会全部存放在./components下
4、编写组件html和js
html即是标准的template写法,不再赘述
js示例如下所示:
define(['app','vueLoader'], (app,loader) => { return { props: ['module', 'toggleIcon', 'thisModule', 'moduleList', 'addModuleListIndex', 'moduleCategoryList', 'iconName'], data(){ return { showElement: false, type: 'tplList', moduleConfig: [ { name: '文字', type: 'wordage', flag: 0, }, { name: '图片', type: 'groupArea', flag: 0, }, { name: '地图', type: 'map', flag: 1, }, { name: '地图2', type: 'map', flag: 1, } ], } }, created(){ console.log('module-list create'); }, mounted(){ console.log('module-list mounted'); }, methods: { //添加模板切换功能加显示对应的模块列表 showModuleList: function (index, moduleName) { app.showModuleList(index, moduleName); }, toggleIcon(){ this.iconName = this.iconName == this.type ? "" : this.type; //加载内容的代码转移到此处 } }, components:{ 'palette-item':loader.load('palette-item'), test:{ template:'123' } } } });