Componentes
En Single File Components (SFC), los tags script
deben especificar el lenguaje ts
:
<script lang="ts">
// usar TypeScript aqui
</script>
Template
<template>
<div>
Name: {{ fullName }}
Message: {{ message }}
</div>
</template>
Script
Vue 2.7
(default since Nuxt 2.16.0
) use:
import { defineComponent, PropType } from 'vue'
interface User {
firstName: string
lastName: string
}
export default defineComponent({
name: 'YourComponent',
props: {
user: {
type: Object as PropType<User>,
required: true
}
},
data () {
return {
message: 'This is a message'
}
},
computed: {
fullName (): string {
return `${this.user.firstName} ${this.user.lastName}`
}
}
})
Vue 2.6
use:
import Vue, { PropOptions } from 'vue'
interface User {
firstName: string
lastName: string
}
export default Vue.extend({
name: 'YourComponent',
props: {
user: {
type: Object,
required: true
} as PropOptions<User>
},
data () {
return {
message: 'This is a message'
}
},
computed: {
fullName (): string {
return `${this.user.firstName} ${this.user.lastName}`
}
}
})
Usando el plugin @vue/composition-api
Instalacion del Plugin
plugins/composition-api.js
import Vue from 'vue'
import VueCompositionApi from '@vue/composition-api'
Vue.use(VueCompositionApi)
nuxt.config.js
export default {
plugins: ['@/plugins/composition-api']
}
La instalación de este plugin es obligatorio para que la función setup
funcione en componentes.
import { defineComponent, computed, ref } from '@vue/composition-api'
interface User {
firstName: string
lastName: string
}
export default defineComponent({
props: {
user: {
type: Object as () => User,
required: true
}
},
setup ({ user }) {
const fullName = computed(() => `${user.firstName} ${user.lastName}`)
const message = ref('This is a message')
return {
fullName,
message
}
}
})
Usando vue-class-component mediante vue-property-decorator
import { Vue, Component, Prop } from 'vue-property-decorator'
interface User {
firstName: string
lastName: string
}
@Component
export default class YourComponent extends Vue {
@Prop({ type: Object, required: true }) readonly user!: User
message: string = 'This is a message'
get fullName (): string {
return `${this.user.firstName} ${this.user.lastName}`
}
}