반응형
Vue js가 잘못된 요소 높이를 반환함
이미지/요소의 높이를 파악해야 합니다.그것은 다음과 같습니다.
mounted() {
this.infoHeight = this.$refs.info.clientHeight + 'px';
}
저장하면 핫 새로고침 시 올바른 높이가 되지만 페이지를 새로 고치면 더 작은/잘못된 값이 반환됩니다.저도 입어봤어요.created()
똑같아요.다른 상황에서는 아무것도 돌려주지 않습니다.
UPDATE(임시 솔루션)
mounted() {
setTimeout(() => this.infoHeight = this.$refs.info.clientHeight + 'px', 100);
}
저도 한번 써봤어요.window.addEventListener('load', () => //todo)
어떤 컴포넌트에서는 동작하고 어떤 컴포넌트에서는 동작하지 않았습니다.
DOM 업데이트 후 를 사용하여 실행해 보십시오.
mounted() {
this.$nextTick(() => { this.infoHeight = this.$refs.info.clientHeight + 'px' });
}
ResizeObserver를 사용하면 보다 깔끔한 방법으로 이 작업을 수행할 수 있습니다.
data: () => ({
infoHeight: 0,
resizeObserver: null
}),
mounted() {
this.resizeObserver = new ResizeObserver(this.onResize)
this.resizeObserver.observe(this.$refs.info)
this.onResize()
},
beforeUnmount() {
this.resizeObserver.unobserve(this.$refs.info)
},
methods: {
onResize() {
this.infoHeight = this.$refs.info.clientHeight + 'px'
}
}
사용할 수 있습니다.this.$watch
와 함께immediate:true
옵션:
mounted () {
this.$watch(
() => {
return this.$refs.info
},
(val) => {
this.infoHeight = this.$refs.info.clientHeight + 'px'
},
{
immediate:true,
deep:true
}
)
}
위의 솔루션은 초기 마운트에서만 작동하며, 다음 마운트에서는 MutationObserver를 사용합니다.
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: '#app',
data: () => ({
infoHeight: 0,
observer: null,
img: "https://images.ctfassets.net/hrltx12pl8hq/6TOyJZTDnuutGpSMYcFlfZ/4dfab047c1d94bbefb0f9325c54e08a2/01-nature_668593321.jpg?fit=fill&w=480&h=270"
}),
mounted() {
const config = {
attributes: true,
childList: true,
subtree: true
};
this.observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation) {
this.infoHeight = this.$refs.info.clientHeight + 'px'
console.log(" changed ", this.$refs.info.clientHeight)
}
});
});
this.observer.observe(this.$refs.info, config);
},
methods: {
changeImg() {
this.img = "https://i.pinimg.com/originals/a7/3d/6e/a73d6e4ac85c6a822841e449b24c78e1.jpg"
},
}
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app" class="container">
<p>{{infoHeight}}</p>
<button class="btn btn-primary" @click="changeImg">Change image</button>
<div ref="info">
<img :src="img" alt="image" />
</div>
</div>
언급URL : https://stackoverflow.com/questions/59545693/vue-js-returning-wrong-element-height
반응형
'programing' 카테고리의 다른 글
길이를 알 수 없는 입력 문자열을 읽으려면 어떻게 해야 합니까? (0) | 2022.07.03 |
---|---|
하위 구성 요소에 대한 v-model 및 하위 구성 요소 Vue 내부의 v-model (0) | 2022.07.03 |
Vue3에 Vuex를 설치하지 못했습니다. (0) | 2022.07.03 |
java.net 를 참조해 주세요.Socket Exception:접속 리셋 (0) | 2022.07.03 |
Vue cli 3 및 IE 11 (0) | 2022.07.03 |