Search⌘ K
AI Features

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.

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:

TypeScript 4.9.5
<template>
<p>Hello World</p>
<p>msg prop = {{ msg }}</p>
<input type="text" v-model="myText" />
<button v-on:click="clicked()">Submit</button>
</template>
<script lang="ts">
import { Options, Vue } from 'vue-class-component';
@Options({
props: {
msg: String
}
})
export default class HelloWorld extends Vue {
msg!: string;
myText!: string;
data() {
return {
myText: this.msg
}
}
clicked() {
console.log(`this.myText = ${this.myText}`);
}
}
</script>

Here, we have made a number of changes to our component:

  • Firstly, we have introduced an input element within our HTML template on line 4 that is using the v-model attribute to bind the value entered in the input control to a property named myText. This binding is a two-way binding, so the value shown on the screen and the internal value of the myText property are kept synchronized.

  • Secondly, we have made is to introduce a button element on line 5, and we have set the v-on:click attribute to a method named clicked(). The v-on attribute is the method that Vue uses to trap DOM events, and in this case, we are trapping the click event.

  • Thirdly, we have introduced a class property named myText of type string on the HelloWorld class on line 19.

  • The fourth change we have made is to create a member function named data on lines 20–24 that returns an object with a property named myText. The ...