UFO ET IT

vuejs에서 구성 요소의 초기 데이터를 재설정하는 적절한 방법이 있습니까?

ufoet 2020. 11. 10. 22:41
반응형

vuejs에서 구성 요소의 초기 데이터를 재설정하는 적절한 방법이 있습니까?


특정 시작 데이터 집합이있는 구성 요소가 있습니다.

data: function (){
    return {
        modalBodyDisplay: 'getUserInput', // possible values: 'getUserInput', 'confirmGeocodedValue'
        submitButtonText: 'Lookup', // possible values 'Lookup', 'Yes'
        addressToConfirm: null,
        bestViewedByTheseBounds: null,
        location:{
            name: null,
            address: null,
            position: null
        }
}

이것은 모달 창의 데이터이므로 표시 될 때이 데이터로 시작하고 싶습니다. 사용자가 창에서 취소하면 모든 데이터를 이것으로 재설정하고 싶습니다.

데이터를 재설정하는 방법을 만들고 모든 데이터 속성을 원래대로 수동으로 설정할 수 있다는 것을 알고 있습니다.

reset: function (){
    this.modalBodyDisplay = 'getUserInput';
    this.submitButtonText = 'Lookup';
    this.addressToConfirm = null;
    this.bestViewedByTheseBounds = null;
    this.location = {
        name: null,
        address: null,
        position: null
    };
}

하지만 이것은 정말 조잡 해 보입니다. 즉, 구성 요소의 데이터 속성을 변경하면 재설정 메서드의 구조를 업데이트해야한다는 것을 기억해야합니다. 그것은 작은 모듈 구성 요소이기 때문에 절대적으로 끔찍한 것은 아니지만 내 두뇌의 최적화 부분을 비명을 지르게 만듭니다.

내가 작동 할 것이라고 생각한 해결책은 ready메서드 에서 초기 데이터 속성을 가져온 다음 저장된 데이터를 사용하여 구성 요소를 재설정하는 것입니다.

data: function (){
    return {
        modalBodyDisplay: 'getUserInput', 
        submitButtonText: 'Lookup', 
        addressToConfirm: null,
        bestViewedByTheseBounds: null,
        location:{
            name: null,
            address: null,
            position: null
        },
        // new property for holding the initial component configuration
        initialDataConfiguration: null
    }
},
ready: function (){
    // grabbing this here so that we can reset the data when we close the window.
    this.initialDataConfiguration = this.$data;
},
methods:{
    resetWindow: function (){
        // set the data for the component back to the original configuration
        this.$data = this.initialDataConfiguration;
    }
}

그러나 initialDataConfiguration객체는 데이터와 함께 변경됩니다 (읽기 메서드 initialDataConfiguration에서 데이터 함수의 범위를 가져 오기 때문에 의미 가 있습니다.

범위를 상속하지 않고 초기 구성 데이터를 가져 오는 방법이 있습니까?

나는 이것을 지나치게 생각하고 있으며 이것을하는 더 나은 / 쉬운 방법이 있습니까?

초기 데이터를 하드 코딩하는 것이 유일한 옵션입니까?


  1. 구성 요소 외부의 함수로 초기 데이터 추출
  2. 해당 기능을 사용하여 구성 요소의 초기 데이터를 설정하십시오.
  3. 필요한 경우 해당 기능을 다시 사용하여 상태를 재설정하십시오.

// outside of the component:
function initialState (){
  return {
    modalBodyDisplay: 'getUserInput', 
    submitButtonText: 'Lookup', 
    addressToConfirm: null,
    bestViewedByTheseBounds: null,
    location:{
      name: null,
      address: null,
      position: null
    }
  }
}

//inside of the component:
data: function (){
    return initialState();
} 


methods:{
    resetWindow: function (){
        Object.assign(this.$data, initialState());
    }
}


data현재 구성 요소 인스턴스에서 구성 요소를 재설정하려면 다음을 시도하십시오.

Object.assign(this.$data, this.$options.data())

Privately I have abstract modal component which utilizes slots to fill various parts of the dialog. When customized modal wraps that abstract modal the data referred in slots belongs to parent component scope. Here is option of the abstract modal which resets data every time the customized modal is shown (ES2015 code):

watch: {
    show (value) { // this is prop's watch
      if(value) {
        Object.assign(this.$parent.$data, this.$parent.$options.data())
      }
    }
}

You can fine tune your modal implementation of course - above may be also executed in some cancel hook.

Bear in mind that mutation of $parent options from child is not recommended, however I think it may be justified if parent component is just customizing the abstract modal and nothing more.


Caution, Object.assign(this.$data, this.$options.data()) does not bind the context into data().

So use this:

Object.assign(this.$data, this.$options.data.apply(this))

cc this answer was originally here


I had to reset the data to original state inside of a child component, this is what worked for me:

Parent component, calling child component's method:

     <button @click="$refs.childComponent.clearAllData()">Clear All</button >

     <child-component ref='childComponent></child-component>

Child component:

  1. defining data in an outside function,
  2. assigning the data object to and outside function
  3. defining the clearallData() method that is to be called upon by the parent component

    function initialState() {
       return { 
         someDataParameters : '',
         someMoreDataParameters: ''
              }
      }
    
    export default {
       data() {
        return initialState();
      },
        methods: {
      clearAllData() {
      Object.assign(this.$data, initialState());
    },
    

If you are annoyed by the warnings, this is a different method:

const initialData = () => ({})

export default {
  data() {
    return initialData();
  },
  methods: {
    resetData(){
      const data = initialData()
      Object.keys(data).forEach(k => this[k] = data[k])
    }
  }
}

No need to mess with $data.

참고URL : https://stackoverflow.com/questions/35604987/is-there-a-proper-way-of-resetting-a-components-initial-data-in-vuejs

반응형