Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue Component - How to handle non-reactive data?

Tags:

vue.js

I'm losing track of reactivity overhead best practices in a Vue 2 Component. I need to generate a one time string with genId() and assign it to the component' id attribute. It seems like overkill to have any watching going on after that.

  1. Is :id="myID" the right way to insert this into the html id?

And then when setting up the source where do I put the non-reactive data? I had 3 thoughts:

  1. Add property myID: genId() to data. But doesn't that add it to the watchlist automatically even though it won't change? Causing overhead?

  2. I read on Vue Forum from a year old answer that myID: genId() should go in the created hook. Are using hooks for this kind of thing a best practice? I thought hooks were discouraged.

  3. Or I could put it in the component methods and then call it directly with :id="genId()

Is there a Vue way to do this?

like image 226
Nathaniel Rink Avatar asked Oct 09 '18 20:10

Nathaniel Rink


People also ask

How do I make Vue data reactive?

To make it reactive we will use “reactive()” function; ##004 we can include also “computed properties” in the reactive object. You can access computed properties accessing to the object properties (game. total in this case);

How do I refresh my Vue component?

The best way to force Vue to re-render a component is to set a :key on the component. When you need the component to be re-rendered, you just change the value of the key and Vue will re-render the component.

Are Vue methods reactive?

Vue comes with the reactive method, which is used to create a reactive state in JavaScript or Vue. Basically, the reactive method is just a function that creates a proxy and wraps it around provided data objects, ultimately turning it into a proxied object.


1 Answers

Use method 2 for non-reactive data (and you use that component many many times on the page that the small overhead of adding the change listeners has any impact.)

created() {
  this.myId = genId()
}

The 3 methods behave differently:

Method 1: data
This will call the genId() when the data object is created and add change listeners.

Method 2: created hook
This will call the genId() when the component object is created and doesn't add change listeners.

Method 3: method
This will call the genId() every time the template re-renders. Which happens every time a change is detected on a variable the view is listening to or a $forceUpdate() is called.

Ps. Vue objects already have a unique id: this._uid
but this is a private property and might change in a future version of Vue.

like image 122
Bob Fanger Avatar answered Oct 25 '22 04:10

Bob Fanger