programing

Vuex에서 동일한 구성 요소에 대해 양방향 데이터 바인딩을 구현하는 다양한 방법

prostudy 2022. 4. 28. 20:35
반응형

Vuex에서 동일한 구성 요소에 대해 양방향 데이터 바인딩을 구현하는 다양한 방법

주소 구성요소가 있는데 주소 양식은 이름, 거리, 도시, 주, 국가와 같은 세부사항으로 되어 있다.나는 그것을 소스목적지에 사용하고 있다.

샘플 템플릿

<div class="row">
    <div class="col-6" id="src">
        <Address :address="src" />
    </div>
    <div class="col-6" id="dest">
        <Address :address="dest" />
    </div>
</div>

주소 구성 요소 나는 (모듈과 함께) Vuex 액션을 사용하여 (주소 데이터를 반환하거나 반환하지 않을 수 있음) API에서 데이터를 가져와 내 스토어 상태에서 돌연변이를 일으킨다.

샘플 상태:

Address:{
    src:{
       name:'',
       street:'',
       city:'',
       state:'',
       country:'',   
    },
    dest:{
       name:'',
       street:'',
       city:'',
       state:'',
       country:'',   
    }
}

나는 돌연변이를 통해 내 상태와 주소 구성요소 사이의 양방향 데이터 바인딩을 달성하고 싶다.

src의 주소 구성요소는 주소.src.(이름, 거리, 도시, 주, 국가)를 주(州), 주소 구성요소는 주소.dest.(이름, 거리, 도시, 주, 국가)를 주(州)로 변경해야 한다.

소품과 방사, vuex 지도 필드로 이 포스트를 따라 해보았지만 소용이 없었다.

나는 그것을 시행하는 적절한 방법이 무엇인지 모르겠다.

나는 이 질문을 어떻게 하는 것이 적절한 방법인가에 대한 도움을 얻기 위해 noob로 게시하고 있다.

만약 내가 너의 문제를 정확히 이해했다면, 나는 아래의 패턴을 따른다.

Make API Call --> data is updated in Vuex --> picked up by computed prop in component

기본적으로 내 구성 요소에서 Vuex 저장소에서 데이터를 가져오는 계산된 받침대를 만들 수 있다.

computed:{
  sourceAddress(){
    return this.$store.state.Address.src;
  },
  destinationAddress(){
    return this.$store.state.Address.dest;
  }
}

그러면 이렇게 계산된 소품을 내 주소 구성요소에 바인딩할 수 있다.

<div class="row">
    <div class="col-6" id="src">
        <Address :address="sourceAddress" />
    </div>
    <div class="col-6" id="dest">
        <Address :address="destinationAddress" />
    </div>
</div>

이제 (API 호출을 통해) Vuex에서 Address 개체가 업데이트될 때마다 이러한 계산된 소품들은 각각 변경 사항을 선택하고 Address 구성 요소를 업데이트한다.

// sample pseudo code

mutations:{

  updateAddress(state, {type,payload}){
    if(type==="destination"){ 
       // update destination address
      }
    else { 
       //update source address
     }
    
  }

},

actions:{

  makeApiCall(context){
    // lets say call succeeds and you have some data to update for destination address
   context.commit('updateAddress',{type:"destination", payload:"data-you-want-to-update});
  }

}

사용할 수 있다vuex getters저장 데이터를 가져올 수 있도록 하십시오.Vue는 데이터를 보다 우아하게 추출하는 방법을 처리한다.two way bindingvuex 도우미 기능을 사용하여 구성 요소에 포함.vuex 도우미 기능에 대한 자세한 내용은 여기를 참조하십시오.

// store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = {
   Address: {
    src: {
       name:'',
       street:'',
       city:'',
       state:'',
       country:'',   
    },
    dest: {
       name:'',
       street:'',
       city:'',
       state:'',
       country:'',   
    }
  }
}

const getters = {
   src: state => state.Address.src,
   desc: state => state.Address.desc
}

const mutations = {
  setSrc(state, srcObj) { // You can play around this to optimize if you can
    state.Address.src = srcObj
  },
  setDesc(state, descObj) {
    state.Address.desc = descObj
  }
}
const actions = {
   makeApiCall({ commit }, { type, params }) {
     yourApiCall(params).then((res) => {
       if (type === 'src') {  // You can play around this to optimize if you can
          commit('setSrc', res)
       } else {
          commit('setDesc', res)
       }
     })
   }
}

export default new Vuex.Store({ state, getters, mutations, actions})
//main.js
// all other imports

import store from './store'

new Vue({
  el: '#app',
  store
})

In your component

<Address :address="src"/>
<Address :address="desc"/>

import { mapGetters, mapActions } from 'vuex'

computed: {
  ...mapGetters(['src', 'desc']) // these are updated automatically when store changes and available on this.src/this.desc 
},
methods: {
  ...mapActions(['makeApiCall']) // you can directly call using this // this.makeApiCall({ type: 'src', params: {} }) 
}

참조URL: https://stackoverflow.com/questions/64520511/different-ways-to-implement-two-way-data-binding-for-same-component-in-vuex

반응형