The power of Vue is in making reactive components child’s play. Well, that is true if the child in question is a 8-year old nephew who knows the basics of Javascript - you know what I mean.
Consider an example that I have used before -
|
|
‘HelloWorld’ is a typical Vue component.
There are two variables used in <template>
.
showHello
is a boolean value that shows the string “World!” whenever a button is clicked (in fact you may notice that it toggles the display at each click)myName
stores the name input in the text box, and the program wishes the said person with utmost courtesy
When you change the variable values the new state gets stored against the variables - as in a ‘normal’ program. In addition, Vue triggers an UI change to reflect the new state without you needing to do anything else.
In fact, you can continuously change variable values and the UI follows through without breaking a sweat. The variables may be changed by user, other components, or a back-end system.
What is this black magic?
Well, that is the power of Vue in action.
Vue tracks the state of the variables and get the browser (or rendering engine) to respond to those changes by changing only specific UI elements.
- The name is displayed with a ‘hello’ only when a value is entered in the input box
- The string ‘world!’ keeps toggling withe clicks
Similarly you could, for example, show the ‘world’ string as well as the message upon a single button click by ‘linking’ the actions like so.
|
|
How to use variables in UI ?
Vue helps us easily tie the UI rendering in <template>
to the variables used in <script>
.
(I am generalizing the use of ‘single file component’, while the use of Vue without SFCs are possible too. Head over to Vue structure at a high-level to know more.)
Flower brackets
The first way of representation is variable within double flower brackets - {{ }}. This way is useful to embed variable values within HTML.
|
|
value
Bind variables one-way.
If variable values changes, the UI changes to reflect the value. However, any change in UI does not go back to the variable itself.
|
|
v-model
This is the most common implementation. v-model has a two-way binding between the UI and the variable in question.
|
|
In fact v-model is a short-hand for -
|
|
.. which typically gets shortened to -
|
|
.. and further simplified (for the programmer) to the v-model version outlined above.
Which binding should I use?
The type you want to use depends on your use case. Prefer one-way binding when variables do not change in UI, or you do not care about the UI changes.
Where should I go next?
Read what real developers never read - docs.