使用TypeScript获取Vue类组件上数据的类型安全性
我从安格鲁到维。我使用类组件,因为我更喜欢语法。我将使用TypeScript获取Vue类组件上数据的类型安全性,typescript,vue.js,vuejs2,vue-component,vue-class-components,Typescript,Vue.js,Vuejs2,Vue Component,Vue Class Components,我从安格鲁到维。我使用类组件,因为我更喜欢语法。我将welcomeMsg用作类属性,因为它将成为组件的数据(请参阅) 我想知道通过TypeScript检查组件的类型来设置组件数据的最佳方法是什么 在我的单元测试(见下文)中,它将允许将123(一个数字)设置为有效值,因为它计算home.$data.welcomeMsg为任何类型。我在类中定义了类似于home.welcomeMsg的东西,但编译器说,在类型Vue上没有这样的成员(我不明白)。即使在console.logginghome之后,其中有一
welcomeMsg
用作类属性,因为它将成为组件的数据(请参阅)
我想知道通过TypeScript检查组件的类型来设置组件数据的最佳方法是什么
在我的单元测试(见下文)中,它将允许将123
(一个数字)设置为有效值,因为它计算home.$data.welcomeMsg
为任何类型。我在类中定义了类似于home.welcomeMsg
的东西,但编译器说,在类型Vue
上没有这样的成员(我不明白)。即使在console.log
ginghome
之后,其中有一个成员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>
我想我做错了什么,但我现在被困了几个小时。。。(顺便说一句,我知道测试失败了)
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,
);
});
});