HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
💌
JJong’s Archive
/
🏞️
Vue
/
플러그인

플러그인

Select
Nov 28, 2023
전역 속성 만들기 ⇒ 어디서든 this.속성이름으로 해당 속성을 접근할 수 있다
 
  1. install(app, options) 메소드에서 플러그인을 작성한다
      • app, options 이름은 아무거나 ㅇㅋ
      • options는 컴포넌트를 use할 때 넘겨받는다
  1. install 내에 app.config.globalProperties.속성이름 으로 전역으로 쓸 속성을 정의한다
      • 속성이름 앞에 $를 붙여주면 좋다
      export default { install(app, options) { app.config.globalProperties.$fetch = (url, opts) => { return fetch(url, opts).then(res=>res.json()) } } }
      plugins/fetch.js
  1. app.use(플러그인이름)으로 해당 플러그인을 등록한다
    1. import { createApp } from 'vue' import App from '~/App' import fetchPlugin from '~/plugins/fetch' const app = createApp(App) app.use(fetchPlugin) app.mount('#app')
      main.js
  1. 이제 아무 곳에서나 this.$속성이름으로 속성을 쓸 수 있다
      • (참고) use로 플러그인을 등록하면 this.$플러그인도 접근할 수 있음
      <template> <h1>{{ msg }}</h1> </template> <script> export default { data() { return { msg: this.fetchData() } }, methods: { async fetchData() { const result = await this.$fetch('https://jsonplaceholder.typicode.com/todos/1') this.msg = result } } } </script>
      App.vue
  • app.use(플러그인이름,옵션객체)으로 옵션 객체를 넘겨줄 수 있고, install에서 options.옵션이름으로 해당 옵션을 받을 수 있음
    • //main.js app.use(fetchPlugin, {name: '$fefe'}) //fetch.js export default { install(app, options) { //options.name이 있으면 그걸쓰고, 없으면 $fetch를 씀 app.config.globalProperties[options.name || '$fetch'] = (url, opts) => { return fetch(url, opts).then(res=>res.json()) } //App.vue await this.$fefe('https://jsonplaceholder.typicode.com/todos/1')
 

 
  • 테스트 api 주소 : https://jsonplaceholder.typicode.com/