0

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>
Donut
  • 63
  • 1
  • 7
  • I think it should be $nextTick instead of $nexttick – Qoyyima Fias Salam Oct 15 '21 at 06:12
  • Please, provide https://stackoverflow.com/help/mcve that can reproduce the problem. This is specific to components you use. The code you posted will reliably have a ref in `mounted` even without nextTick. You don't unsubscribe from the event, the only moment it's possible to not have a ref is when the component has been already unmounted. – Estus Flask Oct 15 '21 at 10:10

1 Answers1

1

There are couple of errors here. First, you are listening using modifyTarget function while you declared the function as modifyTargetDiv. Second, the name of the function is $nextTick and not $nexttick.

Further, you are passing the function to $nextTick instead of passing the arrow function. The this pointer of the traditional function would point to global window object. Arrow function will preserve the this pointer in your callback function.

this.$nextTick(() => { 
  console.log(this.$refs.target);
});
Harshal Patil
  • 17,838
  • 14
  • 60
  • 126
  • A lot of good points. Thanks. However, I didn't make those mistakes in my project. I made up the code snippet on the fly. I think nextTick is not correct in this scenario because of this explanation - "nextTick allows you to execute code after you have changed some data and Vue.js has updated the virtual DOM based on your data change, but before the browser has rendered that change on the page." from - https://stackoverflow.com/questions/47634258/what-is-nexttick-and-what-does-it-do-in-vue-js – Donut Oct 15 '21 at 06:42