Refs, Reactive Objects & Non-Reactive Data
Refs
Refs are the method used to make variables reactive.
First you need to import the ref method from vue -
Then when you declare a variable and assign it to the ref method and pass in its initial value -
This changes the variable into an object so to access it you need to use .value -
Multiple refs can be created, you can use shorthand when grouping these by only using 1 const declaration and then separating them with a comma -
2 Way Data Binding
To enable 2 way data binding you simply use v-model and assign it the relevant ref.
For example the following code has text displayed using a ref -
We can enable 2 way binding by adding an input field and assigning the ref to v-model -
This will add an input field to the page displaying the same default value assigned to the ref that is used in the text field.
Changing the text in the input field will also update the text field (2 way binding).
Reactive Objects
Rather than creating individual refs you can group related variables into a reactive object using the reactive keyword
So for example rather than creating the 2 refs here -
You can create a reactive object to hold both variables (you must first import the reactive method from vue) and access them in your template using dot notation -
Note that in the methods you do not need to use .value to manipulate the data in a reactive object.
Non-Reactive Data
ANy data that you use that does not need to be reactive should be made non-reactive to improve performance.
To create non-reactive data you just declare it without using the ref keyword -