Creating a task management application using Vue 3 Composition API and Typescript with reactivity

I am in the process of creating a simple todo list application using Vue 3 Composition API and TypeScript. Initially, I set up the function for my component to utilize the ref method to manage the reactivity of user input inserted into the listItems array. Now, I'm looking to refactor my setup function to use the reactive method, organizing the properties of my todo app as an object. Within the state object I defined, I set newTodo as an empty string and listItems as an array of strings. The addTodo function is supposed to add newTodo values entered by the user to the listItems array. However, after making these changes, I encountered a parsing error indicating the need for an identifier. This error seems to be targeting the listItems property within the state object: listItems: <string[]>[]. I suspect that this means an id should be included in the state object in order to associate it with each list item dynamically. Do you have any suggestions on how to resolve this issue? Please see the code below:

Template

<template>
  <div class="container">
      <form @submit.prevent="addTodo()">
          <label>New ToDo</label>
          <input
              v-model="state.newTodo"
              name="newTodo"
              autocomplete="off"
          >
          <button>Add ToDo</button>
      </form>

    <div class="content">
      <ul>
        <li v-for="listItem in state.listItems" :key="listItem">
          <h3>{{ listItem }}</h3>
        </li>
      </ul>
    </div>
  </div>
</template>

Script

<script lang="ts">
import { defineComponent, reactive } from 'vue';

export default defineComponent({
  name: 'Form',
  
  setup() {
    const state = reactive({
      newTodo: '',
      listItems: <string[]>[]
    })

    const addTodo = () => {
      state.listItems.push(state.newTodo)
      state.newTodo = ''
    }

    return { state, addTodo }
  }
});
</script>

Answer №1

To implement the generic in reactive, you can do it like this:

const state = reactive<{ newTodo: string; listItems: string[] }>({
  newTodo: "",
  listItems: [],
});

Another way to define the type of listItems is by casting it like so:

const state = reactive({
  newTodo: "",
  listItems: [] as string[],
});

Personally, I find the first solution to be more preferable.

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

As I refreshed the browser page, I encountered an error message from webpack about a connection issue

When I reload my Vue.js single page application on Firefox and Safari, I encountered the following error message in the console (or when submitting a form with post action): The connection with https://localhost:5000/dist/__ webpack_hmr was interrupted wh ...

Utilizing Google Analytics with Laravel Jetstream

Currently, I'm facing challenges with setting up Google Analytics to properly report data with the InertiaJS stack on Laravel Jetstream. My goal is to track individual page visits within this single-page application, but I'm uncertain about the a ...

Exploring object arrays in JavaScript

My jQuery code fetches a data report based on weekdays. I am trying to read an array object returned by ajax, as shown in the script below: <script> export default { data() { return { currentcohortgraphdata: [{"Monday":"0","T ...

In Typescript, interfaces are required to have properties written in Pascal Case instead of camel Case

Currently, I am facing a strange issue in my ASP.NET 5 application where I am using Angular 1.4 with TypeScript and RXJS. Somehow, during the runtime, all my interface properties are getting converted from camel casing to Pascal casing. This unexpected beh ...

The Order ID field in the Serenity-Platform's Order Details tab is not registering orders

I've been working on replicating the functionality of Orders-Order detail in my own project. https://i.stack.imgur.com/Bt47B.png My custom module is called Contract and Contract Line item, which I'm using to achieve this. https://i.stack.imgur ...

Exploring the power of Vue with Cypress testing and streamlining the development process

Currently, I am facing a challenge while trying to run my E2E tests on Gitlab using their CI/CD platform. The issue I'm encountering is the inability to have both my development server and Cypress running simultaneously in order for the E2E tests to ...

Vue's watch function failing to trigger

Experiencing issues with Vue watch methods not triggering for certain objects even when using deep:true. Within my component, I am passed an array as a prop containing fields used to generate forms. These forms are dynamically bound to an object named cru ...

Ways to activate offline assistance with HTML5 history api

Exploring the best strategies to support offline mode using the html5 history api for URL rewrites. How can this be effectively implemented? Consider a hypothetical scenario where a PWA SPA application is hosted at https://abc.xyz, featuring international ...

A guide to customizing node names using vue-slider-component

I am facing an issue with the vue-slider-component. Below is the link to my current test module: template:` <div> <vue-slider v-model="value" :order="false" :tooltip="'always'" :process="false" ...

Building a custom Vue layout within Laravel UI

Currently, I am utilizing Laravel 8 along with laravel/ui 3.4 for the front end of my project. My goal is to establish a fixed sidebar, footer, and a designated area for the router-view. In my routes/web.php file: Route::view('/{any}', 'hom ...

Problem connecting Docker container with Vue Vite

Hello, I recently installed a fresh Vue3 TypeScript + Vite app. However, I am facing an issue after building the image and spinning up the container. I am unable to access localhost:3000 as the browser displays: The connection was reset docker run --rm ...

What's the best way to determine the event type when a mouseDown occurs in React while working on a canvas?

I've been tackling the challenge of incorporating the <canvas /> element into a react project, but I'm encountering difficulties with determining the appropriate event type for it. In my quest for answers, I stumbled upon this insightful ar ...

"Exploring the differences between normalization structures and observable entities in ngrx

I'm currently grappling with the concept of "entity arrays" in my ngrx Store. Let's say I have a collection of PlanDTO retrieved from my api server. Based on the research I've done, it seems necessary to set up a kind of "table" to store th ...

What are the drawbacks of removing comments from polyfills.ts in Angular CLI when using Internet Explorer?

Encountering a similar problem as described in Angular4 Application running issues in IE11. Although the suggested solution resolved the issue, I am left wondering why the lines referring to necessary polyfills for IE9, IE10, and IE11 were initially comm ...

Examining tests for Axios.all and Axios.spread using Jest

I'm having trouble writing JEST test cases for the following method. fetchStudentData (studentList:}[]) { if (studentList.length < 1) { Promise.resolve() } let promises = [] for (const student of StudentList) { if (!st ...

Having trouble with Angular 2 not properly sending POST requests?

Having some trouble with a POST request using Angular 2 HTTP? Check out the code snippet below: import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import 'rxjs/add ...

Exploring TypeScript Compiler Options for ensuring code compliance beyond the confines of strict mode

Our goal is to set up TypeScript Compiler (TSC) with a command line option that can identify errors when developers declare class fields using implicit type expressions instead of explicit ones as illustrated below. class Appliance { //Desired coding ...

Transforming a TypeScript enum into an array of objects

My enum is defined in this structure: export enum GoalProgressMeasurements { Percentage = 1, Numeric_Target = 2, Completed_Tasks = 3, Average_Milestone_Progress = 4, Not_Measured = 5 } However, I want to transform it into an object ar ...

Function arity-based type guard

Consider a scenario where there is a function with multiple optional parameters. Why does the function's arity not have a type guard based on the arguments keyword and what are some solutions that do not require altering the implementation or resorti ...

Issues with VueJS rendering have been observed on MacOS with both Safari and Chrome browsers

Encountering an unusual issue here. My VueJS application, sourced from CDN, incorporates Vuetify. Interestingly, it functions seamlessly on Ubuntu and Windows; however, my client reports observing raw VueJS code when accessing the app via Safari on his iP ...