计算属性中的 document.getElementById [英] document.getElementById in Computed Property
问题描述
我有一个带有 v-if 的组件,它在某个时间点为真/可见.
在计算属性中,我想获取此组件的高度,但不知何故 getElementById 在计算属性中不起作用,即使它作为一种方法工作.
calculateProp: function() {let element = document.getElementById("prop-id")让样式 = window.getComputedStyle(element)返回 style.getPropertyValue("height")},
<块引用>
元素未定义.
具有不同更改的 DOM 元素不是响应式的,因此它们不会触发计算属性,但您可以利用 MutationObserver观察观察到的元素的任何变化:
数据:() =>({计算道具高度:0,观察者:空,}),安装(){let element = document.getElementById("prop-id")this.observer = new MutationObserver((mutations) => {mutations.forEach((mutation) => {如果(突变){让样式 = window.getComputedStyle(element)this.computedProp = style.getPropertyValue("height")}});});this.observer.observe(element, {attributes: true});},beforeDestroy(){this.observer.disconnect()}
I have a component with v-if which is true/visible in some point of time.
Inside a computed property I would like to get the height of this component, but somehow getElementById does not work inside the computed property, even though it works as a method.
computedProp: function() {
let element = document.getElementById("prop-id")
let style = window.getComputedStyle(element)
return style.getPropertyValue("height")
},
element is undefined.
The DOM elements with their different changes are not reactive, so they will not trigger the computed property, but you could take advantage of MutationObserver to watch any change in the observed element :
data: () => ({
computedPropHeight: 0,
observer: null,
}),
mounted() {
let element = document.getElementById("prop-id")
this.observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation) {
let style = window.getComputedStyle(element)
this.computedProp = style.getPropertyValue("height")
}
});
});
this.observer.observe(element, {attributes: true});
},
beforeDestroy(){
this.observer.disconnect()
}
这篇关于计算属性中的 document.getElementById的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!