Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $refs in a computed property

Tags:

vue.js

How do I access $refs inside computed? It's always undefined the first time the computed property is run.

like image 789
Eric Guan Avatar asked Apr 20 '17 23:04

Eric Guan


People also ask

Can I use props in computed?

Computed props can react to changes in multiple props, whereas watched props can only watch one at a time. Computed props are cached, so they only recalculate when things change. Watched props are executed every time.

Can a computed property be async?

This feature is synchronous. However, the vue-async-computed package allows you to create and consume asynchronous computed properties in your components by binding the resolved value of a Promise to a component property.

Can we call a method in computed property?

Computed Caching vs MethodsInstead of a computed property, we can define the same function as a method. For the end result, the two approaches are indeed exactly the same. However, the difference is that computed properties are cached based on their reactive dependencies.

How does a computed property work?

A computed property is used to declaratively describe a value that depends on other values. When you data-bind to a computed property inside the template, Vue knows when to update the DOM when any of the values depended upon by the computed property has changed.


2 Answers

Going to answer my own question here, I couldn't find a satisfactory answer anywhere else. Sometimes you just need access to a dom element to make some calculations. Hopefully this is helpful to others.

I had to trick Vue to update the computed property once the component was mounted.

Vue.component('my-component', {   data(){     return {       isMounted: false     }   },   computed:{     property(){       if(!this.isMounted)         return;       // this.$refs is available     }   },   mounted(){     this.isMounted = true;   } }) 
like image 113
Eric Guan Avatar answered Oct 10 '22 09:10

Eric Guan


I think it is important to quote the Vue js guide:

$refs are only populated after the component has been rendered, and they are not reactive. It is only meant as an escape hatch for direct child manipulation - you should avoid accessing $refs from within templates or computed properties.

It is therefore not something you're supposed to do, although you can always hack your way around it.

like image 25
Geoffroy Avatar answered Oct 10 '22 07:10

Geoffroy