如何解决如何对发送到Vue组件的数据进行类型检查?
可以通过以下方式初始化子类的Vue组件:
let app = new MyApp({
el: '#app',data: {
message: 'Hello Vue!',seconds: 0
},created() {
setInterval(() => {
this.econds = 'asd';
},1000);
}
});
问题在于,Flow和TypeScript都不会注意到错字或this.econds = 'asd';
行上的错误类型。有没有办法解决这个问题?也许使用基于类的组件库?但是然后编译是必需的构建步骤吗?
解决方法
我认为您应该为此正确配置IDE。
我正在使用VSCode和VSCode扩展 Vetur https://github.com/vuejs/vetur
<script lang="ts">
import Vue from 'vue';
export default Vue.extend({
name: 'Home',data: function() {
return {
message: 'Hello Vue!',seconds: 0,};
},created() {
setInterval(() => {
this.econds = 'asd';
},1000);
},});
</script>
与<script lang="ts">
结合使用Vetur为this.econds
告诉您这不存在,并显示以下消息:
类型为'CombinedVueInstance
>>'。 Vet(2551)
不需要编译步骤,它是即时的。
这是您需要的吗?
,因此,如果您使用的是 Typescript ,则可以使用基于类的组件在变量中定义类型。但是,该类型检查仅在编译步骤中进行。 Transpiler仍将正常工作,将生成 Javascript 文件,该文件不会进行类型检查。
另一种方法是使用typeof(variable) === "number"
手动进行类型检查。该表达式将返回true或false,具体取决于variable
的值。
方法1
<script lang="ts">
import { Component,Vue } from 'vue-property-decorator'
@Component({
name: 'Home',})
export default class extends Vue {
message: string = "Hello,Vue";
seconds: number = 0;
created() {
setInterval(() => {
this.seconds = 'asd'; // The transpiler will show an error.
},}
</script>
方法2
<script>
import Vue from 'vue';
export default Vue.extend({
name: 'Home',created() {
setInterval(() => {
let variable = 'asd'
if (typeof(variable) === "number")
this.seconds = variable;
},});
</script>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。