Exploring data properties as a local state
One of the most used terms and reactive elements used when constructing Vue components is data
properties. These manifest themselves within the data()
function of a Vue instance:
<script> Â Â Â Â export default { Â Â Â Â Â Â Â Â data() { Â Â Â Â Â Â Â Â Â Â return { Â Â Â Â Â Â Â Â Â Â Â Â color: 'red' Â Â Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â } Â Â Â Â } </script>
You can use the data()
function to create a local data object to essentially store any information you want to use within your Vue templates. This local object is bound to the component and we call it the local state data of the component. When any property of this local object is updated or changed, it will reactively update in the corresponding template.
Once we have defined our local data, we need to bind it to the template
section to display its values in the UI, which is called data interpolation.
Interpolation is the insertion of something of a different nature into something else. In the Vue context, this is where you would use mustache syntax (double curly braces) to define an area in which you can inject data into a component’s HTML template.
Consider the following example:
<template> Â Â <span> {{ color }}</span> </template > <script> export default { Â Â data() { Â Â Â Â return { Â Â Â Â Â Â color: 'red' Â Â Â Â } Â Â } } </script>
The data
property of red
is bound to Vue.js reactive data and will update during runtime, depending on state changes between the UI and its data.
At this point, we should look at how to define and bind local data in the most classical Vue way. With Vue 3.0, we enjoy a shorter and simpler approach to writing and importing components. Let’s explore it next.