Post

[Vue] Custom Plugin

[Vue] Custom Plugin

여러 번 사용되는 라이브러리의 경우
컴포넌트마다 import 해오지 말고 plugin으로 만들어 사용하면 좋다.
plugin으로 등록하면 전역에서 사용할 수 있다.

Chart.js 라이브러리 plugin 제작

1
$ npm i chart.js
1
2
3
import ChartPlugin from './plugins/ChartPlugin.js';

Vue.use(ChartPlugin);

Vue.use(ChartPlugin) 하게 되면 ChartPlugin 안의 install() 함수가 실행된다.

1
2
3
4
5
6
7
8
import { Chart, registerables } from 'chart.js';
Chart register(...registerables);

export default {
  install(Vue){
    Vue.prototype.$_Chart = Chart;
  }
}

install() 함수가 실행되면
Vue.prototype에 $_Chart라는 이름으로 Chart가 등록된다.
변수명 앞에 $_ 를 프리픽스로 사용하는 이유는 $와 _는 이미 Vue 내부에서 사용되고 있기 때문이다.

1
2
3
4
5
6
7
8
9
export default {
  mounted() {
    const ctx = this.$refs.BarChart;
    new this._Chart(ctx, {
      type: 'bar',
      // ...
    })
  }
}

플러그인으로 등록하면 컴포넌트에서 this.$_Chart로 접근이 가능하다.


참고
This post is licensed under CC BY 4.0 by the author.