Componentes
Em Single File Components (SFC), as tags script
devem especificar a linguagem ts
:
<script lang="ts">
// use TypeScript aqui
</script>
Modelo
<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 o plugin @vue/composition-api
Instalação do 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']
}
Esse registo do plugin é obrigatório para fazer a função setup
funcionar em 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 através do 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}`
}
}