반응형
계산된 속성 내의 $el에 액세스합니다.
접속하려고 합니다.$el.offsetTop 계산 속성에서 위가 되지만 다음 오류가 발생합니다.
Cannot read property 'offsetTop' of undefined
컴포넌트의 offsetTop에 어떻게 액세스 할 수 있습니까?만약 이것이 가능하지 않다면 다른 대안이 있나요?
컴포넌트:
<template>
<div :class="{ 'active' : test }"></div>
</template>
<script>
export default {
computed: {
test() {
console.log(this.$el.offsetTop);
}
}
}
</script>
템플릿에서 계산된 속성이 사용되는 경우 해당 메서드는 Vue 인스턴스가 마운트되기 전에 실행됩니다.this.$el될 것이다undefined.
계산된 속성이 다음 속성에 의존하는 경우this.$el에서 데이터 속성으로 설정할 수 있습니다.mounted(어디서) 후크this.$el정의됩니다).
고객님의 경우:
<template>
<div :class="{ 'active' : test }"></div>
</template>
<script>
export default {
data() {
return { offsetTop: null };
},
computed: {
test() {
console.log(this.offsetTop);
}
},
mounted() {
this.offsetTop = this.$el.offsetTop;
}
}
</script>
이 문제를 해결하기 위해 제가 한 일은 다음과 같습니다.
설정했습니다.el의 재산.null컴포넌트의data마운트된 후크에서this.el로.this.$el그리고 계산한 속성에서 다음 사항을 확인합니다.this.el첫 번째 렌더링 중 오류를 방지하기 위해 해당 속성에 액세스하려고 시도하기 전에 미리 확인하십시오.이 예에서는, 다음과 같이 되어 있습니다.
<template>
<div :class="{ 'active' : test }">{{test}}</div>
</template>
<script>
export default {
data: {
el: null,
},
computed: {
test() {
return this.el ? this.el.offsetTop : 0;
}
},
mounted(){
this.el = this.$el;
}
}
</script>
참고로 Vue.js 계산 속성의 콘솔에 액세스할 수 없다고 생각되므로 해당 비트를 삭제했습니다.
언급URL : https://stackoverflow.com/questions/46451319/access-el-inside-a-computed-property
반응형
'programing' 카테고리의 다른 글
| Vue.js - 로컬 파일에 JSON 개체를 씁니다. (0) | 2022.07.08 |
|---|---|
| 문자열을 반환하는 Spring MVC @Response Body 메서드에서 HTTP 400 오류로 응답하는 방법 (0) | 2022.07.08 |
| 스프링 JPA 특정 컬럼 선택 (0) | 2022.07.08 |
| 부동 소수점이 아닌 정수를 포함하는 경우 이중 변수 선택 (0) | 2022.07.07 |
| 인컴포넌트 내비게이션가드 콜백이 작동하지 않음: Nuxt JS 및 "beforeRouteEnter" (0) | 2022.07.07 |