[TIL # 32] Vue 6일차

Yejin Yang·2022년 5월 26일
0

[TIL]

목록 보기
32/67
post-thumbnail

플러그인 만들기

플러그인을 직접 만들어서 사용하는 일이 은근 많다고 한다. 간단하게 플러그인 만드는 방법을 배웠다.

1 .plugin 폴더를 만들어서 테스트용 js 파일을 만든다.

파일명: test.js

export default {
  install(app) {
    app.config.globalProperties.$test = 123456
  }
}

// test라는 전역속성쓰기: app.vue에서 사용

달러 사인을 붙이지 않으면 반응형데이터인지, 플러그인인지 명확하지 않기 때문에 달러 사인을 붙여준다.

2. main.js에 연결

import { createApp } from 'vue'
import test from './plugins/test'
import App from './App.vue'

createApp(App)
.use($test)
.mount('#app')

플러그인은 use라는 메소드를 사용해서 연결한다.
개발을 하다가 use로 연결되어있는 것을 봤다면, 그건 플러그인 일 것이다.

3. vue파일에 써보기

<template>
</template>

<script>
export default {
  created() {
    console.log(this.$test)
  }

} 
</script>

<style scoped lang="scss">
</style>

store 사용하기

store: 중앙집중화된 데이터 집합소

우리 프로젝트는 모든 데이터들이 집중될 것이다. 프로젝트가 커질수록 복잡해진다. 그래서 모듈로 분리해주는 것이 필요하다.(별도의 파일로 만든다는 의미)

main.js는 연결해주는 기능만 수행하도록 한다.

1. vuex 설치 후 폴더 생성

$ npm i vuex

store 폴더 생성 > index.js 파일 생성

2. main.js 연결

// main.js

import { createApp } from 'vue'
import store from './store/index'
import App from './App.vue'

createApp(App)
.use(store)
.mount('#app')


// index 생략 
import { createApp } from 'vue'
import store from './store'
import App from './App.vue'

createApp(App)
.use(store)
.mount('#app')

index라는 이름은 폴더의 메인이 되는 파일이기 때문에 생략이 가능하다.

Core Concepts

vuex의 중요한 개념 4가지가 있다.

State, Getters, Mutations, Actions

Vue랑 비교하기

: 반응형 데이터(data) 계산된 데이터(computed), 함수(methods)

state ↔ data

getters↔ computed

mutations, actions ↔ methods

유형1. store에 있는 state를 vue파일에 가져오기

// store의 state에 있는 count라는 데이터 가져오기 

<template>
  {{ test }}
</template>

<script>
export default {
  computed: {
    test() {
      return this.$store.state.count
    }
  }
} 
</script>

스토어에서 가져온다 → computed 등록 → 사용(template)

유형2. store에 있는 상태(state) 데이터 수정하기

스토어에게서 가져온 데이터의 수정 권한은 스토어에게만 있다. 왜 그렇게 복잡하게 했을까?

컴포넌트가 많아질수록, 프로젝트가 커질 수록 수정 권한에 제한을 두지 않으면 동시다발적으로 수정이 일어나서 결국 트래킹이 어려워지고 추적이 불가능해진다.

불편함은 있지만 권한을 제한해서 관리하는 것이다.

mutations는 상태를 수정할 권한이 있다.

// index.js
import { createStore } from 'vuex'

export default createStore({
  state() {
    return {
      count: 0
    }
  },

  // state는 바로 위에 작성된 state, this키워드 대신 사용(vuex는 this 키워드 사용 X)
  // count를 증가시키는 로직
  mutations: {
    increase(state) {
     state.count += 1
    }
  }
})

vue파일에서 사용하기
mutation은 commit을 사용해서 호출한다.

<template>
  {{ test }}
  <button @click="increase">
    숫자증가버튼
  </button>
</template>

<script>
export default {
  computed: {
    test() {
      return this.$store.state.count
    }
  },
  methods: {
    increase() {
      // commit(호출) increase 을 호출해주세요. 
      // increase는 스토어에있는 뮤테이션을 호출하게 구성
      this.$store.commit('increase')
    }
  }
}
</script>

mutations은 함수이다. state에 접근할 수 있다.

getter에는 접근은 하지않는 것이 좋다. mutation은 상태에 대한 수정 권한 만 있으면 된다.(접근이 안되는 것이 아니라 안 하는 것)

mutations → state 의 접근이 중요
mutations → Action 접근 x (권한 없음)

유형3. 그 외 로직

state나, 상태를 수정하는 mutations 말고, 통상 그 외 로직은 다 Action 정의한다.

Action은 다른Action에 접근 또는 state, getter, mutations에 접근이 다 가능하다.

Action에 정의한 로직은 dispatch를 사용해서 호출한다.(컴포넌트에서 사용 또는 같은 액션 함수에서 호출)

 actions: {
    increase({ commit }) {
  // 구조분해해서 꺼내기
 // const { state, getters, commit, dispatch } = context
// 한개라서 바로 매개변수에다가 꺼낼 수 있음
      commit('increase')
    }

매개변수는 context 로 접근하면 된다.
const { state, getters, commit, dispatch } = context

객체구조분해로 꺼내서 state, getters, commit, dispatch 따로 사용 가능하다.

profile
Frontend developer

0개의 댓글