Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use computed props in Vue.js with TypeScript?

There is a lot of documentation how to interact with Vue.js using the JavaScript language and just a little about TypeScript. The question is how do you define computed props in a vue component if it is written in TypeScript?

According the official example, computed is an object with functions which will be cached based on their dependent props.

Here is an example I made:

import Vue from 'vue'; import { Component } from "vue-property-decorator";  @Component({}) export default class ComputedDemo extends Vue {     private firstName: string = 'John';     private lastName: string = 'Doe';     private computed: object = {         fullName(): string {             return `${this.firstName} ${this.lastName}`;         },     } } 

And html:

<div>     <h1>Computed props ts demo</h1>     <ul>         <li>First name: {{firstName}}</li>         <li>Last name: {{lastName}}</li>         <li>Together: {{fullName}}</li>     </ul> </div> 

The third list item outputs nothing. Can anybody tell me how to define computed in this case, please?

like image 893
Lev Khruschev Avatar asked Aug 23 '18 09:08

Lev Khruschev


People also ask

Does vue2 support TypeScript?

Vue is written in TypeScript itself and provides first-class TypeScript support. All official Vue packages come with bundled type declarations that should work out-of-the-box.

Should you use TypeScript with Vue?

If you're not using the Vue CLI or do not have a build process, using TypeScript can be a bit too much. But these cases are very few, especially when building apps, like with Ionic Vue. So if you're working with Vue 3, try it out with TypeScript enabled.

Can you call a computed function Vuejs?

You can call a method from computed properties or watchers.


Video Answer


1 Answers

You can use property accessors to declare computed properties. See Vue Class Component. The getter will be triggered as soon as you type in the input.

For example:

<template>     <div>         <input type="text" name="Test Value" id="" v-model="text">          <label>{{label}}</label>     </div>  </template>  <script lang="ts"> import { Component, Vue, Watch } from "vue-property-decorator";  @Component({}) export default class About extends Vue {     private text = "test";      get label() {         return this.text;     } } </script> 

Update for Vue Composition Api

<template>   <div>     <input type="text" name="Test Value" id v-model="text" />      <label>{{label}}</label>   </div> </template>  <script lang="ts"> import { defineComponent, ref, computed } from "@vue/composition-api";  export default defineComponent({   setup() {     const text = ref("test");      const label = computed(() => {       return text.value;     });      return {       text,       label     };   } }); </script> 
like image 137
Jeremy Walters Avatar answered Sep 19 '22 12:09

Jeremy Walters