比如在一个vue项目中,需要重复使用某个方法或是某个数据,可以将该方法/数据封装在一个js文件中,然后在需要使用该方法/数据的.vue文件中直接导入该js文件,使用js文件中的方法/数据。
实现代码:
使用js文件中的方法:
1.js:
export default{
//时间戳转换为正常时间格式
timeStampChange:function(time){
let p = '';
var date = new Date(time); // 获取时间戳
let y = date.getFullYear();
let MM = date.getMonth() + 1;
MM = MM < 10 ? ('0' + MM) : MM;
let d = date.getDate();
d = d < 10 ? ('0' + d) : d;
let h = date.getHours();
h = h < 10 ? ('0' + h) : h;
let m = date.getMinutes();
m = m < 10 ? ('0' + m) : m;
let s = date.getSeconds();
s = s < 10 ? ('0' + s) : s;
p = y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
return p;
}
}
2..vue文件
import timeStampChanges from '@/assets/js/timeStampChange';
this.recordInformation.map(function(item,index){
item.time = timeStampChanges.timeStampChange(item.time);
})
使用js文件中的数据:
1.js:
export const componentType = [
{id: 1, name: '管理节点'},
{id: 2, name: '对等计算节点'},
{id: 3, name: '前置服务节点'},
{id: 4, name: '服务交付节点'},
{id: 5, name: '监督节点'},
{id: 6, name: '上层账本'},
]
2.vue文件:
import {componentType} from '@/assets/js/commonDatas';
components: componentType,
实现效果:

即实现了将时间戳转换为正常时间格式的效果,其他页面需要转换可以直接调用。
注意:
1.使用js文件中的方法:通过import timeStampChanges from '@/assets/js/timeStampChange'; 来导入该js文件,timeStampChanges为该文件的别名,通过别名.(方法)来调用。
2.使用js文件中的数据:通过import {timeStampChange} from '@/assets/js/timeStampChange'; 来导入该js文件,其中{}中的名字即为该js文件中的数据。