首页 > 解决方案 > 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>

标签: typescriptvue.jsvuejs2

解决方案


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>

推荐阅读