[Vue] 전역 플러그인 만들기 (global plugin)

suhanLee·2022년 7월 11일
0

vue-basic

목록 보기
26/29

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) {
		/**
		 *
		 * @param {*} data
		 * @param {*} headers  [['colum1','column2',...]]
		 * @param {*} fields [ {title, list}, {title, list} ]
		 * @param {*} fileName [ {title, list}, {title, list} ]
		 */
		Vue.prototype.excelExport = (data, headers, fields, fileName) => {
			/* 엑셀 데이터 추출 */

			const rsltRow = [];
			data.forEach(row => {
				const setRow = {};
				fields.forEach(field => {
					setRow[field] = row[field]; // setRow['product_nm_dp'] = row['product_nm_dp'];
				});
				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; //[{ wch: max_width }, { wch: max_width }];

			/* 파일명 */
			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);

...(생략)

0개의 댓글