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.
: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:
Add property myID: genId()
to data
. But doesn't that add it to the watchlist automatically even though it won't change? Causing overhead?
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.
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?
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);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With