The Elusive Property of 'this' in Vue Component

My Vue form component, created in TypeScript, functions correctly during runtime but does not pass type-checking. An error is thrown stating that the

property 'title' is not present on the enclosing object type
, which makes sense since it's a reference through v-model. Am I missing something here? Or is it just too much magic for TypeScript to handle? The error specifically points to this line:

body: JSON.stringify({ title: this.title, done: false }),

Here's the complete component code:

<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>

Answer №1

The Vue CLI documentation explains:

To ensure TypeScript can correctly infer types within Vue component options, it is necessary to define components using Vue.component or Vue.extend

Therefore, the code should resemble the following example:

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The default value for prop objects did not set properly

I find myself in a rather peculiar situation: In my HomeComponent.vue <template> <div class="home"> <img alt="Vue logo" src="../assets/logo.png" /> <HelloWorld :msg="msg" @update=" ...

Is it possible to eliminate additional properties from an object using "as" in Typescript?

I am looking for a way to send an object through JSON that implements an interface, but also contains additional properties that I do not want to include. How can I filter out everything except the interface properties so that only a pure object is sent? ...

Opening a file upon launching in Nativescript-Vue: A step-by-step guide

After following the steps outlined in this article, my app is successfully able to open a file with a simple click. Upon launching the application, I see the following message in my console.log: (Foundation) [com.apple.foundation.filecoordination:claims] ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

Error encountered when trying to import Typescript file using a relative path

When attempting to execute src/index.js, I encountered the following error: Error: Cannot find module './utils/spinner' The import statement in index.js appears as follows: const { startSpinner, stopSpinner } = require('./utils/spinner&apos ...

Do you think this is a clever way to circumvent using ENUM for a parameter?

As I continue to explore different coding styles in Typescript and Angular, I recently encountered a method without any comments attached to it. It seems like this method is enforcing that the value passed in must be one of the defined options, but strang ...

[Vue alert]: Issue with rendering: "TypeError: Unable to access property 'replace' of an undefined value"

I'm currently working on a project similar to HackerNews and encountering the following issue: vue.esm.js?efeb:591 [Vue warn]: Error in render: "TypeError: Cannot read property 'replace' of undefined" found in ---> <Item ...

Vue.js blocks the use of iframes

I've come across a peculiar issue where I need to embed an iframe inside a Vue template and then be able to modify that iframe later. The code snippet below shows the simplified version of the problem: <html> <body> <div id="app" ...

The condition of the variable not being bound

<button id="btn1"> Button 1 </button> <button id="btn2" v-if="state == 2"> Button 2 </button> export default { data() { return { emailPreferences: { isLoading: false ...

There is an issue with the type candidate in the Notion API, resulting in

In this instance, the troublesome code causing issues is displayed below: import {Client, LogLevel} from "@notionhq/client"; const notion = new Client({ auth: process.env.NOTION_TOKEN, logLevel: process.env.NODE_ENV !== 'product ...

Exploring Quasar app environment variables

I am having trouble accessing an environment variable. I have tried creating a .env file and setting the variable as VUE_APP_TOKEN: 11token22, but when I try to log it with console.log, it returns undefined. Next, I attempted to set the environment variab ...

Steps to resolve the error message 'Argument of type 'number' is not assignable to parameter of type 'string | RegExp':

Is there a way to prevent users from using special symbols or having blank spaces without any characters in my form? I encountered an error when trying to implement this in my FormGroup Validator, which displayed the message 'Argument of type 'nu ...

Guide to utilizing axios.request(config) in Vue.js

I have been attempting to use Axios in my vue.js project to make HTTP requests. Despite reviewing the Axios documentation on GitHub and exploring various examples online, I have yet to find a solution. My goal is to create a configuration file where I can ...

Issues with importing Vue.js test units in spec files are causing difficulties

Upon reviewing a demo project, it is evident that: src components ShoppingList.spec.js ShoppingList.vue store __mocks__ index.js index.js ShoppingList.spec.js import { __creareMocks as createMocks ...

What is the best way to create a TypeScript type for React props that only allows prop B to be used if prop A is included in the component?

My component Text has 2 props: isHideable: boolean and hidden: boolean. How can I only allow Hidden as a prop when isHideable is set to true? Currently, both isHideable and hidden are being accepted which is not the desired behavior: type Props = { chi ...

Using RadSideDrawer with Typescript in Vue class components: A Step-by-Step Guide

I am attempting to integrate external components into Vue Typescript Class Components. Following the installation of the standard template, I made modifications to its <script> block based on this guide: import { Vue, Component, Prop } from "vue-pro ...

Oops! Looks like drizzle-orm ran into a hiccup trying to convert the "created_at" column to a timestamp without a time zone

This is the content of my schema.ts file: export const messages = pgTable("messages", { id: serial("id").primaryKey(), chatId: integer("chat_id") .references(() => chats.id) .notNull(), content: text("con ...

Tips for utilizing vue-class-component

<script lang="ts"> import { defineComponent, ref, nextTick, unref, onMounted } from 'vue'; import { useScript } from '/@/hooks/web/useScript'; const BAI_DU_MAP_URL = 'https://api.map.baidu.com/getscript?v=3.0& ...

Encountering a bug in Angular 10 while attempting to assign a value from

I am having trouble updating the role of a user. In my database, I have a user table and a role table with a ManyToMany relation. I can retrieve all the values and even the correct selected value, but I am encountering issues when trying to update it. Her ...

Tips for refreshing Vue.js component content using methods?

I am currently facing an issue with re-initializing some input data within my component using a method. Despite being confident in the correctness of the syntax, I encounter an error during code compilation. Can anyone spot the error or provide an explanat ...