src/plugins/TestPlugin.js
const TestPlugin = {
install(Vue, options) {
console.log(options);
Vue.prototype.globalHelper = () => {
alert('Hello world');
};
},
};
export { TestPlugin };
main.js
import Vue from 'vue';
...(생략)
import { TestPlugin } from '@/plugins/TestPlugin.js';
Vue.use(TestPlugin);
...(생략)
views/Test.vue
<button @click="globalHelper">클릭!</button>
엑셀 다운로드
src/utils/excelUtil.js
const XLSX = require('xlsx');
const excelUtil = {
install(Vue) {
Vue.prototype.excelExport = (data, headers, fields, fileName) => {
const rsltRow = [];
data.forEach(row => {
const setRow = {};
fields.forEach(field => {
setRow[field] = row[field];
});
rsltRow.push(setRow);
});
const worksheet = XLSX.utils.json_to_sheet(rsltRow);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, 'Dates');
XLSX.utils.sheet_add_aoa(worksheet, [headers], {
origin: 'A1',
});
const max_width_list = [];
fields.forEach(field => {
max_width_list.push({
wch: rsltRow.reduce((w, r) => Math.max(w, r[field].length), 10),
});
});
worksheet['!cols'] = max_width_list;
XLSX.writeFile(workbook, `${fileName}.xlsx`);
};
},
};
export { excelUtil };
src/views/TestExcel.vue
<template>
<div>
<button @click="downloadExcel">다운로드</button>
<br />
<button @click="sampleExcel">샘플다운로드</button>
</div>
</template>
<script>
export default {
methods: {
async downloadExcel() {
var formData = new FormData();
formData.append('currPage', '1');
formData.append('pageSize', '10');
const { data } = await this.$store.dispatch(
'FETCH_GET_PRODUCT_LIST',
formData,
);
const headers = ['상품이름', '상품코드'];
const fields = ['product_nm_dp', 'product_cd'];
this.excelExport(data.productPageList, headers, fields, 'myFile');
},
sampleExcel() {
const headers = ['휴대전화'];
const fields = ['sample_mobile'];
this.excelExport(
[{ sample_mobile: '01000000000' }],
headers,
fields,
'sample',
);
},
},
};
</script>
main.js
import Vue from 'vue';
...(생략)
import { excelUtil } from '@/utils/excelUtil.js';
Vue.use(excelUtil);
...(생략)