一、全局组件
新建一个组件文件夹,如cp。
- 组件文件
在cp文件夹中新建vue组件文件,如cp.vue
//cp.vue
<template>
<div></div>
</template>
<script>
export default {
name: 'cp',
data() {
return {}
},
methods: {},
mounted() {}
}
</script>
<style scoped></style>
- 组件入口文件
在cp文件夹中新建vue组件入口文件,index.js,这里一定要注意把入口文件名定义为index.js,方便调用。
//index.js
import cp from './src/cp'
cp.install = function (Vue) {
Vue.component(cp.name, cp)
}
export default cp
- 注册全局组件
在主入口文件main.js中注册全局组件。
//main.js
//引入全局组件文件
import cp from './components/global/cp'
Vue.use(cp);
二、全局过滤器
- 过滤器文件
在src文件夹下的config文件夹下新建filters.js过滤器文件。
//filters.js
//性别过滤器
const judgeSex = (val) => {
let sex = [{code:0,name:'男'},{code:1,name:'女'}];
let str = '';
sex.forEach((item) => {
if(parseInt(val) == item.code) {
str = item.name;
}
});
return str;
}
//题目类型过滤器
const judgeQuestionType = (val) => {
let type = '';
switch (parseInt(val)){
case 1:
type = '单选题';
break;
case 2:
type = '多选题';
break;
case 3:
type = '判断题';
break;
default:
type = '未定义';
break;
}
return type;
}
//导出过滤器函数
export default {
judgeSex,
judgeQuestionType
}
- 注册全局过滤器
在主入口文件main.js中注册全局过滤器。
//引入全局过滤器文件
import filters from './config/filters.js';
//过滤器统一处理加载
Object.keys(filters).forEach(key => {
Vue.filter(key, filters[key])
})
三、全局函数
- 函数文件
在src文件夹下的config文件夹下新建methods.js函数文件。
//methods.js
/**
* @desc 生成随机参数
* updatedDate:2018.09.07
*/
const random = {
/**
* @desc 随机获取颜色
* @param {number} opacity 透明度
* @return {String}
*/
color: function(opacity) {
var rgba_x = [];
for(let i = 0; i < 3; i++) {
rgba_x[i] = Math.floor(Math.random() * 255);
}
if(opacity) {
return 'rgba(' + rgba_x[0] + ',' + rgba_x[1] + ',' + rgba_x[2] + ',' + opacity + ')';
} else {
return 'rgb(' + rgba_x[0] + ',' + rgba_x[1] + ',' + rgba_x[2] + ')';
}
}, //随机获取颜色-end
/**
* @desc 随机获取颜色列表
* @param {number} length 数量
* @param {number} opacity 透明度
* @return {String}
*/
colorList: function(length,opacity) {
let colorx = [];
for (let i = 0 ; i < length ; i++) {
let color = this.color();
if ( colorx.includes(color) ) {
i--;
} else{
colorx[i] = color;
}
}
return colorx;
}, //随机获取颜色列表-end
/**
* @desc 生成指定范围的随机数
* @param {Number} min
* @param {Number} max
* @return {Number}
*/
num: function(min, max) {
var minx, maxx;
if(min && max) {
minx = min;
maxx = max;
} else {
minx = 0;
maxx = 10000;
}
return Math.floor(Math.random() * (maxx - minx + 1)) + minx;
} //生成指定范围的随机数-end
}//生成随机参数操作-end
const MyMethods = {};
MyMethods.install = function (Vue) {
// 添加实例方法
Vue.prototype.$methods= methods;
};
export default MyMethods
- 注册全局函数
在主入口文件main.js中注册全局函数。
//引入全局函数
import methods from './config/methods.js'
//注册全局函数
Vue.use(Five);
世上没有绝望的处境,只有对处境绝望的人。