typescript - Vue 组件中缺少 this 的属性
问题描述
我有简单的 Vue 表单组件,用 TypeScript 编写。当我运行它时它可以工作,但不会进行类型检查。它说property 'title' is not present on the enclosing object type
,这当然是真的,因为它是一个v-model
参考。难道我做错了什么?还是 TypeScript 无法处理的魔法?错误发生在以下行:
body: JSON.stringify({ title: this.title, done: false }),
这是整个组件:
<template>
<form>
<label>
Title
<input type="text" v-model="title">
</label>
<input type="button" value="Submit" v-on:click="submitData()">
</form>
</template>
<script lang="ts">
export default {
name: "TodoForm",
data: function () {
return { title: "" }
},
methods: {
submitData: function() {
fetch('http://localhost:8000/api/v1/todo/', {
method: "POST",
headers: new Headers({"Content-Type": "application/json"}),
body: JSON.stringify({ title: this.title, done: false }),
})
}
}
}
</script>
解决方案
Vue CLI文档状态:
要让 TypeScript 正确推断 Vue 组件选项中的类型,您需要使用
Vue.component
或定义组件Vue.extend
所以,它应该看起来像这样:
<script lang="ts">
import Vue from 'vue';
export default Vue.extend({
data() {
return {
title: ''
}
},
methods: {
submitData() {
console.log(this.title)
}
}
})
</script>
推荐阅读
- python - 该算法的算法复杂度,用于查找长度为 X 的所有有序排列
- java - 在 Java 和 Python 中使用相同的时间格式
- android - URL 在 Chrome 中加载完美,但在 FinestWebView 中不加载
- matlab - 将矩阵转换为数组
- android - 模拟器:错误:“Nexus_4_API_27”的快照操作处于挂起状态,超时已过期。退出
- ajax - 类型“AjaxControlToolkit.HtmlEditorExtender”没有名为“EnableSanitization”的公共属性
- angular - 我们可以将 C++ dll 直接集成到 ionic 框架中吗
- javascript - 用于在用户键入和复制粘贴时删除金额浮点输入字段中的空格的正则表达式
- c# - 如何在 OpenTK 中裁剪圆形区域(小地图!)
- solr - Apache Solr 修复最大编号。每个请求的文件