MST

星途 面试题库

面试题:Vue 2与Vue 3在TypeScript支持上,数据声明方式有何改进

请阐述在Vue 2中使用TypeScript进行数据声明的方式,以及Vue 3相较于Vue 2,在数据声明使用TypeScript时做出了哪些改进,并分别举例说明。
24.1万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

Vue 2中使用TypeScript进行数据声明的方式

  1. 使用 Vue.extend 构造器 通过 Vue.extend 方法创建一个Vue组件构造器,在其中使用TypeScript定义数据类型。
import Vue from 'vue';

const Component = Vue.extend({
  data() {
    return {
      message: 'Hello, Vue 2 with TypeScript!',
      count: 0
    };
  },
  methods: {
    increment() {
      this.count++;
    }
  }
});

new Component().$mount('#app');
  1. 使用装饰器(需要额外配置支持装饰器的环境) 安装 vue-class-component 库,使用装饰器语法定义组件。
import Vue from 'vue';
import Component from 'vue-class-component';

@Component
export default class MyComponent extends Vue {
  message: string = 'Hello, Vue 2 with TypeScript!';
  count: number = 0;

  increment() {
    this.count++;
  }
}

Vue 3相较于Vue 2,在数据声明使用TypeScript时做出的改进

  1. setup 函数与 Composition API Vue 3引入了 setup 函数和 Composition API,使得逻辑复用和代码组织更为灵活。在 setup 函数中声明数据更加直观。
import { defineComponent, ref } from 'vue';

export default defineComponent({
  setup() {
    const message = ref('Hello, Vue 3 with TypeScript!');
    const count = ref(0);

    const increment = () => {
      count.value++;
    };

    return {
      message,
      count,
      increment
    };
  }
});
  1. 更好的类型推导 在Vue 3中,setup 函数返回的对象类型能被更好地推导。例如在模板中使用 messagecount 时,TypeScript能准确知道它们的类型,减少类型标注的工作量。
  2. DefineComponent 类型 defineComponent 函数返回的类型更加准确,有助于在使用组件时进行类型检查。例如:
import { defineComponent } from 'vue';

const MyComponent = defineComponent({
  name: 'MyComponent',
  setup() {
    // ...
  }
});

// 在父组件中使用MyComponent时,TypeScript能进行更准确的类型检查
  1. Prop 类型定义更简洁 在Vue 2中定义 Prop 类型可能比较繁琐,Vue 3中通过 PropType 能更简洁地定义。
// Vue 2
import Vue from 'vue';
import { PropType } from 'vue';

interface Person {
  name: string;
  age: number;
}

const Component = Vue.extend({
  props: {
    person: {
      type: Object as PropType<Person>,
      required: true
    }
  }
});

// Vue 3
import { defineComponent } from 'vue';
import { PropType } from 'vue';

interface Person {
  name: string;
  age: number;
}

export default defineComponent({
  props: {
    person: {
      type: Object as PropType<Person>,
      required: true
    }
  }
});

在Vue 3中,结合 setup 函数,接收 Prop 也更方便和类型安全。

import { defineComponent, PropType } from 'vue';

interface Person {
  name: string;
  age: number;
}

export default defineComponent({
  props: {
    person: {
      type: Object as PropType<Person>,
      required: true
    }
  },
  setup(props) {
    const greeting = `Hello, ${props.person.name}! You are ${props.person.age} years old.`;
    return {
      greeting
    };
  }
});