I am trying to create a small vue app that modifies a hello world div when the screen size is changed.
I mounted a listener to the component that listens for viewport resizing. If the viewport changes, it then calls a function that modifies hello world div, modifyTargetDiv()
.
In modifyTargetDiv()
, I use this.$nextTick
which is not right since this keyword doesn't wait for the component to finish rerendering. Hence, I sometimes get refs hasn't rendered yet and other time refs rendered. My question is what is the correct vue feature that always gives me refs rendered. Thank you.
Note: I have looked into vue updated() hook but viewport resize doesn't trigger it. Also, mounted() hook only runs one time when the component first renders so it won't work with the viewport resizing.
<template>
<div ref="target"> Hello world </div>
</template>
<script>
mounted() {
window.addEvenListener('resize', this.modifyTargetDiv);
},
methods: {
modifyTargetDiv() {
this.$nextTick(() => {
if (this.$refs.target == null) {
console.log(`refs hasn't rendered yet`);
} else {
console.log('refs rendered');
// do something with the div
// this.$refs.target.getHeight()
}
});
}
}
</script>