On gists
Sledování změn na $refs prvku
•
Popular ⭐
Vue.js
Foo.vue
Raw
#
<template>
<div ref="el" style="height: 70px" :style="computedStyles">
<slot />
</div>
<hr />
height {{ height }}
<br />
Computed {{ computedHeight }}
<hr />
<button @click="changeHeight(150)">150</button>
<button @click="changeHeight(200)">200</button>
<button @click="changeHeight(250)">250</button>
</template>
<script>
export default {
data() {
return {
height: null,
isMounted: false,
};
},
computed: {
computedStyles() {
if (this.isMounted && this.height) return { height: this.computedHeight, background: 'limegreen' };
return { background: 'pink' };
},
computedHeight() {
if (this.isMounted && this.height) return this.height + 'px';
return null;
},
},
methods: {
changeHeight(h) {
//console.log('BEFORE', this.height);
this.height = h;
//console.log('AFTER', this.height);
},
observeElement() {
const el = this.$refs.el;
const observer = new MutationObserver(mutationsList => {
for (const mutation of mutationsList) {
if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
console.log('Element style changed:', el.style.height);
}
}
});
observer.observe(el, { attributes: true });
},
},
mounted() {
this.isMounted = true;
this.height = this.$refs.el.style.height;
this.observeElement(); // Spustíme sledování změn výšky elementu
},
};
</script>