source

VueJS 계산 데이터를 소품으로 전달하면 정의되지 않은 상태로 반환됨

goodcode 2022. 8. 29. 22:08
반응형

VueJS 계산 데이터를 소품으로 전달하면 정의되지 않은 상태로 반환됨

여러 번 시도해 봤지만, 문제가 뭔지 알 수가 없어요.다른 곳에서 읽을 수 있는 내용에서는 자 컴포넌트에 전달된 변수는 다음과 같이 전송됩니다.undefined데이터를 부모에서 사용할 수 있게 되기 전에.

자세한 내용은 여기를 참조해 주세요.

코드 앤 박스 내의 코드

<template>
  <div id="app">
    <child :parentData="data.message"/>
  </div>
</template>

<script>
import Child from "./components/Child";

export default {
  name: "App",
  components: {
    Child
  },
  computed: {
    quote() { return 'Better late than never' }
  },
  data() {
    return {

      data: { message: this.quote } ,

    thisWorks: { message: "You can see this message if you replace what is passed to the child"  }

    };
  }

};
</script>

그 후 자녀:

<template>
  <div>
  <h1>I am the Child Component</h1>
  <h2> {{ parentData }}</h2>
  </div>
</template>

<script>
export default {
  name: "Child",
  props: {            
      parentData: { type: String, default: "I don't have parent data" },   
  },
};
</script>

정답은 다음과 같은 값에 액세스할 수 없습니다.this.quote왜냐하면 그 순간에는data object작성 중,computed object실제로 존재하지 않습니다.

이것은 대체 수단입니다.created()값을 갱신하는 라이프 사이클 훅data object:

  created(){
    this.data = {
      message: this.quote
    }
  },

변경은 필요 없습니다.코드 라인을 추가하는 것만으로 충분합니다.

당신의 CodeSandbox 프로젝트에서 이미 그 코드들을 테스트해 봤는데 아주 잘 작동합니다.

도움이 됐으면 좋겠네요!

언급URL : https://stackoverflow.com/questions/52518395/vuejs-passing-computed-data-as-a-prop-returns-undefined

반응형