...

/

Computed Properties, Conditional Statements, and Arrays

Computed Properties, Conditional Statements, and Arrays

Learn how to work with computed properties, conditional statements, and array looping in Vue components.

Computed properties and conditional statements

Vue components also allow us to define what are known as computed properties, which are read-only and are derived from some component logic. Along with computed properties, we are also able to define conditional statements in our HTML templates and deal with arrays of data within a template loop. As an example of this, let’s update our HelloWorld component as follows:

Press + to interact
<template>
<p>Hello World</p>
<p>msg prop = {{ msg }}</p>
<input type="text" v-model="myText" />
<button v-on:click="clicked()">Submit</button>
<div v-if="stringLength > 0">
<p>text length is : {{ stringLength }}</p>
<ul>words are :
<li v-for="word in words">{{word}}</li>
</ul>
</div>
</template>
<script lang="ts">
import { Options, Vue } from 'vue-class-component';
@Options({
props: {
msg: String
},
computed: {
stringLength() {
return this.myText.length;
},
words() {
return this.myText.split(' ')
}
},
emits: ["onSubmitClicked"]
})
export default class HelloWorld extends Vue {
//... existing class
}
</script>

We have updated our HTML template and added a <div> element on lines 6–11 that uses a v-if attribute, which will render if the conditional statement ...