programing

VUE/VUEX: 부모 템플릿에서 자식 템플릿으로 데이터를 전달하는 방법

prostudy 2022. 8. 22. 21:32
반응형

VUE/VUEX: 부모 템플릿에서 자식 템플릿으로 데이터를 전달하는 방법

VUE 2.0 VUEX를 사용하는 경우 데이터 전송 방법을 약간 헷갈립니다.parent로.child.

<template>
  <div id="app" class="container">
    <div class="card" v-for="(triad, index) in triads">
      <div class="row">
        <div class="col-sm-4">
          <people />
        </div>
        <div class="col-sm-4">
          <places />
        </div>
        <div class="col-sm-4">
          <equipment />
        </div>
      </div>
    </div>
  </div>
</template>

"triads"라는 이름의 어레이를 루프하고 있습니다.

state: {
  triads: [
    {
      people: [],
      places: [],
      equipment: []
    }
  ]
}

송신하고 싶다triad에 가변적인.<people />,<places />그리고.<equipment />.


콘텐츠를 부모 템플릿에서 자녀 템플릿으로 가져오려면 어떻게 해야 합니까?감사합니다.

하위 구성요소에 PROP를 추가한 다음 데이터를 바인딩하기만 하면 됩니다.

예.<people :yourProp='triad'>

하위 구성 요소(https://vuejs.org/v2/guide/components.html#Props)에 따라):

Vue.component('people', {
  // declare the props
  props: ['yourProp'],
  // just like data, the prop can be used inside templates
  // and is also made available in the vm as this.message
  template: '<span>{{ yourProp }}</span>'
})

데이터 전달에만 vuex가 필요하지 않습니다.Vuex가 구성 요소 간에 상태를 공유해야 합니다(양방향).

소품으로 재산을 물려줄 수 있다

<template>
  <div id="app" class="container">
    <div class="card" v-for="(triad, index) in triads">
      <div class="row">
        <div class="col-sm-4">
          <people :someproperty='triad'></people>
        </div>
        <div class="col-sm-4">
          <places :someproperty='triad'></places>
        </div>
        <div class="col-sm-4">
          <equipment :someproperty='triad'></equipement>
        </div>
      </div>
    </div>
  </div>
</template>

각 자 컴포넌트 안에서 다음과 같은 소품을 언급합니다.

export default {
  props: ['someproperty']
}

상위 컴포넌트도 속성에 직접 액세스할 수 없기 때문에 상위 컴포넌트 내의 mapGetters를 사용하여 액세스할 수 있습니다.또한, 자신의 주에도 getter가 있습니다.

state: {
  triads: [
    {
      people: [],
      places: [],
      equipment: []
    }
  ]
},
getters: {
  getTriads: (state) => {
     return state.triads
  }
}

이제 부모에서 mapGetters를 사용할 수 있습니다.

import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters({
      'triads': 'getTriads'
    })
  }
}

너무 무리한 설정이라면, 이것만 시험해 보세요.

export default {
  computed: {
    triads () {
     /**
     * You could also try, return this.$store.state.triads
     * but DONT do that, that defeats the purpose of using vuex.  
     */
      return this.$store.getters.getTriads 
    }
  }
}

언급URL : https://stackoverflow.com/questions/42225779/vue-vuex-how-to-pass-data-from-parent-template-to-child-template

반응형