Potato

Vuex의 index.js의 state를 통해 데이터를 전달하는 방법을 간단하게 코드를 구현해보았다.

 

 

 

컴포넌트 구성

 

 

 

App.vue에서 AChild, BChild라는 두 개의 하위 컴포넌트를 가지고 있음

<!-- App.vue -->

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <div id="box">
      <AChild msg="하위 A 컴포넌트"/>
      <BChild msg="하위 B 컴포넌트"/>
    </div>
    
  </div>
</template>

<script>
import AChild from './components/AChild'
import BChild from './components/BChild'

export default {
  name: 'App',
  components: {
    AChild,
    BChild
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  margin-top: 60px;
}

#box {
  border : solid 1px gray;
}
</style>

 

AChild에서

O버튼을 누르면 yes 데이터 전달

X버튼을 누르면 no 데이터 전달

 

<!-- AChild.vue -->

<template>
  <div>
    <h1>{{ msg }}</h1>

    <button @click="Yes">O</button>
    <button @click="No">X</button>
  </div>
</template>

<script>
export default {
  name: 'AChild',
  props: {
    msg: String
  },
  methods: {
    Yes() {
      this.$store.dispatch('send','yes')
    },
    No() {
      this.$store.dispatch('send','no')
    }
  },
}
</script>

<style>

</style>

 

 

index.js에서

actions(비동기 작업이 없으므로 생략 가능) -> mutations -> state순으로 데이터 전달

//index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    mystate: '입력없음'
  },
  getters: {
  },
  mutations: {
    SEND(state, data) {
      state.mystate = data
    }
  },
  actions: {
    send(context,data) {
      context.commit('SEND', data)
    } 
  },
  modules: {
  }
})

 

index.js에 있는 mystate의 값이 변할 때(계산될 때) 마다 화면에 출력해야 하므로 computed를 이용해 출력 

<!-- BChild.vue -->

<template>
    <div>
      <h1>{{ msg }}</h1>
      <h3>현재상태 : {{ change }}</h3>
    </div>
  </template>
  
  <script>
  export default {
    name: 'BChild',
    props: {
      msg: String
    },
    computed: {
      change() {
         return this.$store.state.mystate
      }
    }
  }
  </script>
  
  <style>
  
  </style>

 

+ Recent posts