플러그인은 일반적으로 Vue에 전역 수준의 기능을 추가할 때 사용하는 기능을 말합니다. 예를 들어, 전역적으로 사용할 유틸리티 함수, 전역 컴포넌트 등록, 디렉티브, 또는 HTTP 클라이언트(axios) 같은 외부 라이브러리를 Vue와 통합할 수 있습니다.
플러그인에 대해 엄격하게 정의 된 범위는 없으나, 유용한 시나리오는 아래와 같습니다.
등록
// MyPlugin.js
export default {
install(app, options) {
// 전역 컴포넌트 등록
app.component('MyButton', {
template: `<button><slot></slot></button>`
});
}
};
사용
<template>
<div>
<MyButton>Click Me</MyButton>
</div>
</template>
등록
// MyPlugin.js
export default {
install(app, options) {
// 커스텀 디렉티브 등록
app.directive('focus', {
mounted(el) {
el.focus();
}
});
}
};
사용
<template>
<div>
<input v-focus placeholder="This input is auto-focused" />
</div>
</template>
(focus라는 이름으로 등록하여 v-focus로 사용)
등록
// MyPlugin.js
export default {
install(app, options) {
// 리소스 주입
app.provide('myGlobalValue', options.value || '기본 값');
}
};
사용
<template>
<div>
Injected Value: {{ injectedValue }}
</div>
</template>
<script>
import { inject } from 'vue';
export default {
setup() {
const injectedValue = inject('myGlobalValue'); // 'myGlobalValue'를 주입받음
return { injectedValue };
}
};
</script>
등록
// MyPlugin.js
export default {
install(app, options) {
// 전역 속성 추가
app.config.globalProperties.$myGlobalMethod = function (message) {
console.log(`Global method says: ${message}`);
};
}
};
사용
<template>
<div>
<button @click="sayHello">Say Hello from Global Method</button>
</div>
</template>
<script>
export default {
methods: {
sayHello() {
// 전역 메서드 호출
this.$myGlobalMethod('Hello from the component!');
}
}
};
</script>
위에서 작성한 기능을 모두 포함한 플러그인을 하나로 합쳐서 플러그인으로 등록할 수 있습니다.
// MyPlugin.js
export default {
install(app, options) {
// 전역 컴포넌트 등록
app.component('MyButton', {
template: `<button><slot></slot></button>`
});
// 커스텀 디렉티브 등록
app.directive('focus', {
mounted(el) {
el.focus();
}
});
// 리소스 주입
app.provide('myGlobalValue', options.value || '기본 값');
// 전역 속성 추가
app.config.globalProperties.$myGlobalMethod = function (message) {
console.log(`Global method says: ${message}`);
};
}
};