programing

다른 데이터 속성에서 Vuejs 데이터 속성에 액세스하는 방법

sourcetip 2022. 7. 14. 23:23
반응형

다른 데이터 속성에서 Vuejs 데이터 속성에 액세스하는 방법

이것들은 나의 코드이다.

data: {
     cat1 : {name: "Category 1", reference : false},
     cat2 : {name: "Subcategory 2", reference: this.cat1}
}

함수에서 이.cat2.reference를 호출하면 값이 false가 됩니다.나는 cat1을 어딘가에 선언하고 여기에 언급하고 싶지 않다.cat2 레퍼런스를 완벽하게 얻을 수 있도록 위와 같은 구조를 원합니다.

아무나 저에게 어떤 해결책이라도 조언해 주실 수 있나요?

한 가지 옵션은 다음과 같습니다.datagetter 메서드를 사용한 오브젝트

예를들면

new Vue({
  el: '#newUser',
  data: () => { // make sure to use a "data" function
    // initialise with a declared variable
    const formData = {
      cat1, // not sure where these come from
      cat2,
      cat3,
      cat5: { name: 'Subcategory 5', get reference() { return formData.cat1 }}
    }
    return { formData }
  }
}

데모 ~ https://jsfiddle.net/ztfgapxh/

계산된 속성을 사용하는 것이 좋을 것 같습니다.

data: {
  cat1 : {name: "Category 1", reference : false}
}
computed: {
  cat2() {
    return {name: "Subcategory 2", reference: this.cat1}
  }
}

이제 전화를 걸 수 있습니다.this.cat1그리고.this.cat2단, cat1이 변경될 때마다 cat2가 갱신됩니다.

https://vuejs.org/v2/guide/computed.html

편집: 모든 것을 처리할 경우catX일관된 방법으로 모든 속성을 계산하도록 할 수 있습니다.

참조를 this.data.cat1을 반환하는 함수로 설정할 수 있습니다.

data: {
     cat1 : {name: "Category 1", reference : ()=> {return null;}},
     cat2 : {name: "Subcategory 2", reference: ()=> {return this.data.cat1;}}
}

cat2의 참조를 취득하려면 함수로서 호출해야 합니다.

var referenceOfCat2 = this.data.cat2.reference();
//referenceOfCat2 = {name: "Category 1", reference : ()=> {return null}}

컴포넌트 외부에서 이 함수를 호출하려고 해도 동작하지 않습니다.cat2를 다른 컴포넌트에 전달하려면 전달하기 전에 참조를 설정해야 합니다(ref 함수 호출). 그렇지 않으면 다른 컴포넌트에 도달하면 데이터 타깃이 동일하지 않고(일부 변경을 하지 않는 한) reference()가 작동하지 않습니다.

언급URL : https://stackoverflow.com/questions/62647810/how-to-access-a-vuejs-data-property-from-another-data-property

반응형