【问题标题】:Missing Property of this in Vue componentVue 组件中缺少 this 的属性
【发布时间】:2019-11-12 07:03:35
【问题描述】:

我有一个简单的 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>

【问题讨论】:

  • 你能在沙盒上重现错误吗?

标签: typescript vue.js vuejs2


【解决方案1】:

Vue CLI docs 状态:

要让 TypeScript 正确推断 Vue 组件选项中的类型,您需要使用 Vue.componentVue.extend 定义组件

所以,它应该看起来像这样:

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
  data() {
    return {
      title: ''
    }
  },
  methods: {
    submitData() {
      console.log(this.title)
    }
  }
})
</script>

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 2019-12-19
    • 2019-11-05
    • 2019-02-14
    • 1970-01-01
    • 2018-01-06
    • 2020-11-12
    • 2016-08-15
    • 1970-01-01
    相关资源
    最近更新 更多