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?
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.
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.
You can call a method from computed properties or watchers.
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>
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With