티스토리 뷰

개발일기

vuex로 데이터 전달하기

삐삐들의 주인 2021. 10. 15. 17:53

데이터를 전달시켜야 하는데 상위 컴포넌트 말고 아예 다른 컴포넌트로 전달을 시켜야 했다.

그래서 찾아보다가 vuex를 발견. 

 

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    menuType : ''
  },
  mutations: {},
  actions: {},
  modules: {},
});

store.js를 생성하여 만들어준다.

지금 사용하는 프로젝트에서는 store/index.js 안에 생성이 되어있어서 따로 생성할 필요는 없었다.

import Vue from "vue";
import store from "./store";

export const eventBus = new Vue()

Vue.config.productionTip = false;

new Vue({
  store,
}).$mount("#app");

main.js 에서 store를 붙여준다.

 

 

값을 보내야 하는 컴포넌트에서 

 this.$store.state.menuType = 'hook'

이렇게 입력을 해주었다. 

클릭의 경우 hook 이라는 string을 전달하도록 했다. 

 

또한 radio 를 클릭시 실시간으로 변경이 되게 해야 했기 때문에 computed와 watch를 사용해주었다. 

   watch :{
        exampleFunction(){
            if(this.$store.state.menuType == 'hook') {
                this.hooker = true
            } else {
                this.hooker = false
                
            }
        }
       
        
        },
    computed : {
        exampleFunction(){return this.$store.state.menuType}
    },

이러한 식으로 데이터를 받아야 하는 컴포넌트에 추가를 해주면 된다.

 

공지사항
최근에 올라온 글
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31