学习Vue 03-03 为TypeScript使用defineComponent支持

03 为TypeScript使用defineComponent支持

The defineComponent() method is a wrapper function that accepts an object of configurations and returns the same thing with type inference for defining a component.

defineComponent() 方法是一个封装函数,它接受一个配置对象,并通过类型推断返回同样的对象,用于定义组件。

The defineComponent() method is available only in Vue 3.x onward and relevant only when TypeScript is required.

defineComponent() 方法仅在 Vue 3.x 及以后版本中可用,并且仅在需要使用 TypeScript 时才有用。

Example 3-3 illustrates using defineComponent() to define a component.

例 3-3 演示了如何使用 defineComponent() 来定义组件。

<template>
    <h2 class="heading">{{ message }}h2>
template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
    name: 'MyMessageComponent',
    data() {
        return {
            message: 'Welcome to Vue 3!'
        }
    }
});
script>

If you use VSCode as your IDE, and have Volar extension installed, you will see the type of message as string when hovering on message in the template section, as shown in Figure 3-3.

如果您使用 VSCode 作为集成开发环境,并安装了 Volar 扩展,那么在模板部分将鼠标悬停在消息上时,就会看到消息类型为字符串,如图 3-3 所示。

学习Vue 03-03 为TypeScript使用defineComponent支持_第1张图片

You should use defineComponent() for TypeScript support only in complex components such as accessing a component’s properties through this instance. Otherwise, you can use the standard method for defining an SFC component.

只有在使用复杂组件(如通过此实例访问组件属性)时,才应使用 defineComponent() 来支持 TypeScript。否则,您可以使用标准方法来定义 SFC 组件。

In this book, you will see a combination of the traditional component definition approach and defineComponent() when suitable. You are free to decide which method works best for you.

在本书中,你将看到传统组件定义方法和 defineComponent() 方法的结合。你可以自由决定哪种方法最适合你。

Next, we will explore the lifecycle of a component and its hooks.

接下来,我们将探讨组件及其钩子的生命周期。

你可能感兴趣的:(学习Vue,typescript,学习,vue.js)