Component State and Events
Explore how to manage internal state in Vue components using TypeScript, implement two-way data binding with v-model, and emit events to parent components. Understand setting up event handlers in parent components to react to child events and see data flow in real time through practical examples.
We'll cover the following...
Component state
The properties that a component exposes to a parent component are read-only. This means that only the parent component can change these properties and that the flow of data is one-way, from parent to child. If our component needs to maintain its own state and update an internal property, such as the value from an input control, we will need a place to store this state. Vue components use a function named data that returns a structure for storing the internal state.
Let’s update our HelloWorld component and introduce an internal property named
myText as follows:
Here, we have made a number of changes to our component:
-
Firstly, we have introduced an
inputelement within our HTML template on line 4 that is using thev-modelattribute to bind the value entered in the input control to a property namedmyText. This binding is a two-way binding, so the value shown on the screen and the internal value of themyTextproperty are kept synchronized. -
Secondly, we have made is to introduce a
buttonelement on line 5, and we have set thev-on:clickattribute to a method namedclicked(). Thev-onattribute is the method that Vue uses to trap DOM events, and in this case, we are trapping theclickevent. -
Thirdly, we have introduced a class property named
myTextof typestringon theHelloWorldclass on line 19. -
The fourth change we have made is to create a member function named
dataon lines 20–24 that returns an object with a property namedmyText. The ...