Assign a value to an object within a Vue data property

Hey there, I am currently learning vuejs and facing an issue with setting an object value to a vue data property.

  data: () => ({
    newTodo: "",
    todoObj: { title: newTodo, undo: false },
    toDoList: [
      { title: "Study", undo: false },
      { title: "Work", undo: false },
      { title: "Gaming", undo:false }
    ],
  }),
  methods: {
    addNewToList() {
      this.toDoList.push(this.todoObj);
      this.newTodo = "";
    },
  },
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.4/vue.js"></script>

I am trying to bind newTodo to the input and then add the object to an array. However, newTodo is showing as undefined. Please suggest if you have a better approach for achieving this functionality.

Thank you in advance!

Answer №1

In my opinion, it would be more efficient to eliminate the use of todoObj and simply incorporate this line into your method:

this.todoList.push({value: this.newTodo, undo: false})

This approach reduces the need for declaring an additional variable.

The issue arises from this section of code: { title: newTodo, undo: false }

Answer №2

A useful approach is to design a template specifically for tasks of this nature.

<script>
  const newTodoTemplate = {
    title: '',
    undo: false,
  }
  export default {
    name: 'Index',
    data: () => ({
      todoObj: { ...newTodoTemplate },
      toDoList: [
        { title: "Study", undo: false },
        { title: "Work", undo: false },
        { title: "Gaming", undo: false },
      ],
    }),
    methods: {
      addNewToList() {
       this.toDoList.push(this.todoObj);
       this.todoObj = { ...newTodoTemplate }
      },
  },
}
</script>

Using this template system, the todoObj always mirrors the template object. When adding to the list, you are essentially carrying over the template through the todoObj.

This method allows you to input a new task in todoObj.title, and after pushing it to the list, the previous task will be automatically reset as you're duplicating the template.

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

One typical approach in React/JavaScript for monitoring the runtime of every function within a program

Experimenting with different techniques such as performance.now() or new Date().getTime() has been done in order to monitor the processing time of every function/method. However, specifying these methods within each function for time calculation purposes h ...

Rails confirmation feature malfunctioning

I have been struggling to figure out where I am going wrong with this code even though I've checked several posts. I am using Ruby on Rails and trying to run the following snippet: <%= link_to 'Destroy', article_path(article), ...

Pressing a button meant to transfer text from a textarea results in the typed content failing to show up

Having trouble with a custom text area called a math field. I'm currently interning on a project to build a math search engine, where users can input plain text and LaTeX equations into a query bar. The issue I'm facing is that sometimes when th ...

What is the proper way to utilize the setState() function in ReactJS?

I am new to the world of ReactJS and I have been exploring the concepts of state and setState(). While trying to implement a name change using setState(), I found myself wondering where exactly in my code should I invoke the setState() method: Should I c ...

Code activates the wrong function

Below is a snippet of HTML and JS code for handling alerts: HTML: <button onclick="alertFunction()">Display Choose Option Modal</button> <button onclick="alertFunction2()">Display Veloce Modal</button> JS: function alertFunct ...

Upon installation, the extension that replaces the new tab fails to detect the index.html file

edit: Check out the Chrome Extension here Edit 2: It seems that the recent update containing the index.html file was not published due to Google putting it under revision. Apologies for forgetting to include the index.html file in the upload zip, as I ...

How to implement PayPal integration in PHP

I am currently working on integrating the paypal payment system into a website dedicated to pet adoption. Initially, I had a basic code structure that was functional. However, after making some modifications and additions to the code, it no longer redirect ...

Having trouble inputting text into input field using ReactJS

I am currently facing a challenge while attempting to modify the value of an input field using ReactJS. The issue I am encountering is the inability to input values into the field. After reviewing several other queries, it appears that simply changing the ...

Update the browser value using AJAX without the need to refresh the page

After retrieving a value from an XML file using ajax jquery, I encountered an issue. When I change the value in my XML file, it does not automatically update in the browser. <?xml version="1.0"?> <count><number>5</number></count ...

Learn the process of eliminating objects from an array of objects using a foreach loop in PHP

After retrieving a list of users from the database, the data looks like this: [ { "id":1, "name":"Bob", "category":"admin", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82f6e7f1f6 ...

Incorporating Meteor js into an established user system

I'm completely new to the world of Meteor and I am looking to integrate it with my current system that relies on a MongoDB database. As I explore Meteor, I have discovered that there are packages like accounts-facebook and accounts-twitter which assis ...

Customizing functions in JavaScript with constructor property

What is the best way to implement method overriding in JavaScript that is both effective and cross-browser compatible? function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; ...

Calculate the sum of two multidimensional arrays and store the result in a new array by adding together all the

I am looking to merge two multidimensional arrays together, re-indexing them if necessary. These arrays were created within a foreach loop and will be used for batch insert queries. Here are the arrays that I would like to combine: Array ( [1] => ...

Receiving server data with socket.io in Node.js

I have set up a Node.js server to send data to an HTML client using socket.io: var spawn = require('child_process').spawn; var child = spawn('node', ['file.js']); child.stdin.write("Hello there!"); child.stdout.on(&apo ...

Retrieve an object that includes a property with an array of objects by filtering it with an array of strings

I have a large JSON file filled with data on over 300 different types of drinks, including their ingredients, names, and instructions. Each object in the file represents a unique drink recipe. Here is an example of how one of these objects is structured: ...

AngularJS retrieve data from JSON (like using MySQL)

My data is in JSON format: {"sectionTitle":"Account Information","sectionItems":[{"itemTitle":"Balance","url":"/account/balance","selected":true},{"itemTitle":"Account Statement","url":"/account/statementsearch","selected":false},{"itemTitle":"Deposit","u ...

Is it feasible to activate an action on a click of a Vimeo video?

Is there a way to activate an event by clicking if a video is set with background=1 and has no controls? This particular video is from Vimeo, using a plus account which allows for setting background=1. The scenario involves a Vimeo video playing on loop ...

Is it possible for the 'error' attribute to be deemed invalid or inappropriate within ajax?

I am encountering an issue with my mobile cordova application. When attempting to log in, I am facing the following error: Error: JavaScript runtime error - Object doesn't support property or method 'error' The error is being traced back t ...

Guide on integrating AJAX and coding in WordPress using PHP

I created a search box in PHP and it is functioning correctly. However, when I try to integrate it into WordPress, it does not work as expected. It seems like the AJAX functionality is not working properly within WordPress. I would like to add this search ...

When my script is located in the head of the HTML page, I am unable to

My goal is to make my JavaScript code function properly when I insert it into either the head or body elements of an HTML document. Let's look at some examples: First, I insert the script into the body as shown in this example (works correctly): ...