组件
在使用 单文件组件 (SFC) 时, script
标签须指定成 ts
语言。
<script lang="ts">
// 这里编写 TypeScript 代码
</script>
模板
<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}`
}
}
})
使用 @vue/composition-api 插件
插件安装方法
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']
}
此插件注册后,setup
才能在组件中产生作用。
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
}
}
})
通过 vue-property-decorator 来使用 vue-class-component
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}`
}
}