Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to type a computed property in the new composition API?

Tags:

Im playing along with the new Vue plugin for using composition API and TypeScript and there is something I'm not quite understanding.

How am I supposed to type computed properties?

import Vue from 'vue' import { ref, computed, Ref } from '@vue/composition-api'  export default Vue.extend({   setup(props, context) {      const movieName:Ref<string> = ref('Relatos Salvajes')     const country:Ref<string> = ref('Argentina')      const nameAndCountry = computed(() => `The movie name is ${movieName.value} from ${country.value}`);      return { movieName, country, nameAndCountry }   } }) 

In this simple example I'm declaring two refs and a computed property to join both. VSC is telling me that computed properties are returning ReadOnly type... But I can't make it work.

like image 246
pegido Avatar asked Mar 25 '20 19:03

pegido


People also ask

How do you define props in Vue composition API?

You define a prop named disabled in MyComponent. vue . ... and then add the component like this, passing in disabled . Note that :disabled="true" and just disabled mean the same thing in both cases - when props are defined or not.

What is computed in vue3?

Computed properties are another powerful feature from Vue that allows us to transform or perform calculations on our data and then easily reuse the result as an up-to-date variable in our template. Computed properties are very useful and should replace complex in-template expressions.


2 Answers

There are two different types for that.

If your computed prop is readonly:

const nameAndCountry: ComputedRef<string> = computed((): string => `The movie name is ${movieName.value} from ${country.value}`); 

if it has a setter method:

const nameAndCountry: WritableComputedRef<string> = computed({   get(): string {     return 'somestring'   },   set(newValue: string): void {     // set something   }, }); 
like image 94
acme Avatar answered Sep 21 '22 23:09

acme


I believe you should go with using generics:

const movieName = ref<string>("Relatos Salvajes") const country = ref<string>("Argentina")  const nameAndCountry = computed<string>(   () => `The movie name is ${movieName.value} from ${country.value}` ) 
like image 29
Damon Avatar answered Sep 22 '22 23:09

Damon