HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
👻
개발 기록
/
📑
강의 정리
/
📑
플러그인 ~ Vuex(Store)
📑

플러그인 ~ Vuex(Store)

Created
Oct 8, 2021 10:03 AM
Type
Vue
Mento
레온
Created By

플러그인

원하는 동작을 정의해서 필요한 곳에서 쉽게 사용할 수 있음.

플러그인 만드는 방법

fetch 플러그인 만들기

  • 전체 애플리케이션에서 사용할 수 있는 키를 translate하는 함수를 만들기 때문에 app.config.globalProperties를 사용하여 노출.
  • return에 원하는 동작 구현.
  • createApp()을 사용하여 Vue 앱을 초기화 한 후 use() 메서드를 호출하여 애플리케이션에 플러그인을 추가 할 수 있음.

믹스인

  • Vue 컴포넌트에 재사용할 때 사용.
  • 믹스인과 컴포넌트 자신은 중복되는 옵션을 가지고 있는 경우에는 병합됨.
  • 이때 충돌하는 키가 있을 경우 컴포넌트가 우선권을 가짐.
notion image
 
👉 간단한 설문조사 만들기 실습코드

Teleport

👉 간단한 모달 만들기 실습코드

Provide, Inject

  • 부모 컴포넌트는 데이터 제공을 위해 provide 옵션을 사용.
  • 자식 요소는 데이터 사용을 위해 inject 옵션을 사용.
  • 컴포넌트 계층 구조의 깊이와 상관없이 모든 자식에 대한 종속성 제공자 역할을 함.
  • 단 provide로 제공하는 데이터는 반응성을 가지지 않음.
  • 이를 위해 사용하는 패턴이 vue 패키지에서 computed 함수를 가져와 콜백으로 데이터를 전달.
⚠️
props와 emit과 연관시키는 것이 아닌 조상 컴포넌트로부터 후손 컴포넌트로 데이터를 내려주는 것에 집중.

Vuex(Store)

  • Vuex는 Vue.js 애플리케이션에 대한 상태 관리 패턴 + 라이브러리임 (중앙 집중화된 저장소).
  • 공통의 상태를 공유하는 여러 컴포넌트는 코드가 복잡해짐.
Vuex 상태 관리 패턴.
Vuex 상태 관리 패턴.
  • state(데이터)로 vue components로 가져와 화면에 출력함.
  • mutations는 상태를 변경함.
  • actions는 mutations의 상태 변경 외 모든 로직을 처리함. ex) api 통신.
  • getters는 상태를 계산해야 할 때 사용. ex) computed

설치하기

  1. 버전 4로 이동.
  1. vscode 터미널에서 npm install vuex@next --save
  • state(데이터)는 함수로 만들어야 함.
  • app.use(store)를 사용함으로써 $store키워드 사용 가능.
  • actions에서 사용하는 첫 번째 매개변수로 context가 있음.
    • state - 상태를 참조.
    • getters - 계산된 상태를 참조.
    • commit - mutation을 실행.
    • dispatch - 다른 action을 실행.

모듈 방식

  • 관리가 용이함.
  • namenamespaced를 true로 등록해야 함.
 왼쪽 모듈화 전, 오른쪽 모듈화 후
왼쪽 모듈화 전, 오른쪽 모듈화 후
count와 message는 namespaced임.
count와 message는 namespaced임.

mapping

  • 상단의 개별 등록 대신 map 키워드를 사용하여 한 번에 가져올 수 있음.
    • mapState
    • mapGetters
    • mapMutations
    • mapActions
  • 전역에 등록된 namespaced가 없는 데이터는 이름 없이 데이터만 입력하면 됨.
notion image
export default { install: (app, options) => { // 플러그인 코드는 여기에 } }
export default { install(app, options) { app.config.globalProperties.$fetch = (url, opts) => { return fetch(url, opts).then((res) => res.json()); }; }, };
fetch.js
import fetchPlugin from "~/plugins/fetch"; const app = createApp(App); app.use(fetchPlugin); app.mount("#app")
main.js
export default { created() { this.init(); }, methods: { async init() { const res = await this.$fetch( "https://jsonplaceholder.typicode.com/todos" ); console.log(res); }, }, };
App.vue
// mixin을 사용할 어플리케이션 정의 const app = Vue.createApp({ mixins: [myMixin] })
export default { data() { return { count: 1, msg: "mixin Hi", }; }, };
<template> <h1 @click="msg += '!!'"> {{ msg }} </h1> <Parent /> </template> <script> import Parent from "~/components/Parent"; import { computed } from "vue"; export default { components: { Parent, }, provide() { return { msg: computed(() => this.msg), }; }, data() { return { msg: "hello vue", }; }, }; </script>
App.vue
<template> <h1>Parent</h1> <Child /> </template> <script> import Child from "~/components/Child"; export default { components: { Child, }, }; </script>
Parent.vue
<template> <h1>Child</h1> {{ msg.value }} </template> <script> export default { inject: ["msg"], }; </script>
Child.vue
import { createApp } from 'vue' import App from '~App' import store from '~/store/index' const app = createApp({ App }) // Install the store instance as a plugin app.use(store) app.mount('#app')
vuex 코드 패턴 main.js
import { createStore } from 'vuex' export default createStore({ state () { return { count: 0 } }, mutations: { increment (state) { state.count++ } } })
src/store/index.js
actions: { async fetchTodos({ commit }) { const todo = await fetch('api address').then(res => res.json()) commit('updateMsg', todo.title) } }
actions 활용 예제