使用 TypeScript 获取 Vue 类组件上数据的类型安全

问题描述

我从 Angular 转到 Vue。我使用类组件,因为我更喜欢它的语法。我将 welcomeMsg 用作类属性,因为它将成为组件的数据(请参阅 Vue Class Components)。

我想知道通过 TypeScript 检查它的类型来设置组件数据的最佳方法是什么。

在我的 UnitTest(见下文)中,它将允许将 123一个数字)设置为有效值,因为它将 home.$data.welcomeMsg 评估为 any 类型。我还希望在类中定义 home.welcomeMsg 之类的东西时可以访问它,但是编译器说,类型 Vue 上没有这样的成员(我不明白)。即使在 console.logging home 上有成员 welcomeMsg 之后。

Home.vue

<template>
  <div class="welcome">
    <p class="welcome-message">{{ welcomeMsg }}</p>
  </div>
</template>

<script lang="ts">
import { Component,Vue } from 'vue-property-decorator';

@Component
export default class Home extends Vue {
  welcomeMsg = 'Welcome to the App';
}
</script>

Home.spec.ts

import Home from '@/components/Home.vue';

describe('Home.vue',() => {
  let home: Home;

  beforeEach(async () => {
    home = new Home();
    //console.log(home);
    home.$mount();
  });

  afterEach(() => {
    home.$destroy();
  });

  it('should show welcome message',async () => {
    const welcomeMsg = 'Welcome to my App';
    home.$data.welcomeMsg = 123; # <- should not allow a number
    await home.$nextTick();
    expect(home.$el.querySelector('.welcome-message')?.textContent).toEqual(
      welcomeMsg,);
  });
});

我想我在做一些明显的错误,但我现在被卡住了几个小时......(顺便说一句,我知道所提供的测试失败了)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)