What is the method for incorporating input value into a li list item?

I am attempting to insert the content of an input as a list item (<li>) in an unordered list (<ul>).

I managed to add it by connecting the value to the array list of list items. However, it disappears when I clear the input field. How can I resolve this issue?

HTML code:

<div id="app">
  <h1>{{ message }}</h1>
  <form v-on:submit.prevent="addNewTodo">
    <input type="text" v-model="todo.task">
    <button type="submit">Add todo</button>
  </form>

  <ul>
    <li v-for="todo in todos" :class="{ completed: todo.isActive }" @click="$set(todo, 'isActive', !todo.isActive)">
     {{ todo.task }} <span v-on:click="deleteTodo">{{ todo.delete }}</span>
    </li>
  </ul>
</div>

JS Code:

var app = new Vue({
  el: '#app',
  data: {
    message: 'List of things to do today',
    todos: [
      { task: 'Have breakfast', delete:'(x)'},
      { task: 'Go to the gym', delete:'(x)'},
      { task: 'Study Vuejs', delete:'(x)'}
    ],
    todo: {task: '', delete: '(x)'}
  },
  methods: {
    addNewTodo: function(){
      this.todos.push( this.todo );
    },
    deleteTodo: function(){
      this.todos.shift( this.todo )
    },
  }
});

Here is an example JSfiddle link for reference: https://jsfiddle.net/mercenariomode/gwd34815/1/

Answer №1

To update the object reference, consider binding the "v-model" to the "task" property for better functionality.

Here is an example of HTML code:

<form v-on:submit.prevent="addNewTodo">
    <input type="text" v-model="task">
    <button type="submit">Add todo</button>
</form>

And here is a snippet of JS Code:

el: '#app',
  data: {
    message: 'List of things to do today',
    todos: [
      { task: 'Have breakfast', delete:'(x)'},
      { task: 'Go to the gym', delete:'(x)'},
      { task: 'Study Vuejs', delete:'(x)'}
    ],
    task: '',
}

Remember to add logic for adding an object to the array in the addNewTodo method:

addNewTodo: function(){
        let todo = {task: this.task, delete: '(x)'};
        this.todos.push(todo);

        this.task = ''; // clear input field
},

For more information and demonstration, check out this JSFiddle link: https://jsfiddle.net/nm29yq7d/1/

Answer №2

It is important to properly clone the property you are referencing, here is a suggested way to do it:

 let t={};
 Object.assign(t,this.todo)
 this.todos.push( t );

An issue in your code is that you are deleting the wrong todo item. To rectify this, pass the index of the selected todo to the deleteTodo method like this :

 <ul>
    <li v-for="(todo,i) in todos" :class="{ completed: todo.isActive }" @click="$set(todo, 'isActive', !todo.isActive)">
      {{ todo.task }} <span v-on:click="deleteTodo(i)">{{ todo.delete }}</span>
    </li>
  </ul>

To delete the specified todo item, use this.todos.splice(i,1);:

 deleteTodo: function(){
      this.todos.splice(i,1);
    }

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

Encountering error message "Module not found '@angular/compiler-cli/ngcc'" while attempting to run "ng serve" for my application

Encountering an error while trying to run my app, I have attempted various solutions available online. These include uninstalling and reinstalling angular/cli, verifying the correct version in package.json (ensuring it is "@angular/cli" and not "@angular-c ...

Troubleshooting the issue of Ajax POST not properly sending the model data to the controller in ASP.NET Core

I've been attempting to send POST data to my controller from a Kendo dialog event, but I keep encountering the issue of the model being null. Despite trying multiple solutions mentioned on StackOverflow, none have proven effective. Here is my Ajax ca ...

AngularJS Table Checkbox Selection Helper Functions

I am feeling completely lost and could really use some assistance. I have been looking at different examples but nothing seems to be helping me out. I have created a dynamic table with checkboxes. Whenever a row is selected, its id gets added to an array ...

Initiate a fresh start with an automatic input reset

When you perform an action in the first id = "benodigheden", I believe there should be a specific outcome that then triggers a second rule for id = "benodigheden". However, I have been unsuccessful in finding information on this topic online. It seems like ...

Utilize Server Side Includes in your JavaScript code

When the query string is parsed, a specific section of code SSI is included in the footer page. Here are some examples of query strings: ?headId=520&genderType=2 ?headId=600&genderType=1 function GetQueryStringParams(sParam){ var sPageURL ...

Invoke the mounted lifecycle once more

At the moment, my table is set up to use the v-for directive to populate the data: <table v-for="(data, idx) in dataset" :key="idx"> </table> Following that, I have two buttons that perform actions in the database, and I wa ...

The jQuery script is malfunctioning

I have implemented an order form where users must complete a captcha code verification for cash on delivery. I am using jQuery to validate the entered captcha code. If the entered captcha code is incorrect, I prevent the user from submitting the form and ...

Despite being listed in the entry components, HelloComponent is not actually included in the NgModule

Check out my StackBlitz demo where I am experimenting with dynamically instantiating the HelloComponent using the ReflexiveInjector. The HelloComponent is added to the app modules entryComponents array. Despite this setup, I am still encountering the foll ...

Is it not possible to change node labels in D3.js after clicking on a node?

After being inspired by this link, I successfully created a basic network visualization app using D3.js. The app reads node names from a textarea on an HTML page and then constructs a network where all nodes are interconnected. All the relevant code can ...

How can Vue.js update the displayed information when the selection option changes?

Ensuring the total weight of the products remains accurate when changing the unit of measurement is essential. Currently, although the data in the array is being updated, these changes are only reflected on the screen after clicking on other input fields. ...

Syntax error: Unexpected character encountered in JavaScript code

Although this question has been asked numerous times before, I have not been able to find a solution that applies to my specific situation. I am currently working on a chat system that involves sending and receiving messages. Here is my PHP code: < ...

Removing an element from an array within MongoDB

After closely examining my mongodb data structure, it appears like this: [ { "_id": "582bc918e3ff1bf021ae8b66", "boardName": "Test Board", "created_at": 1479264483957, "__v": 0, "person": [ { "name": "Steve", "w ...

Retrieving values from all fields in a dynamic form using VuejsLet's say

In the process of developing an admin panel using Vuejs and tailwind CSS for managing exercises on a page, I have encountered some challenges. My current objective is to insert the dynamic form values into a Firebase real-time database. However, I am stru ...

Can the layout component receive events from other components?

Consider this scenario: you have a Header component that is imported in layout/main.vue. In the Header component, you define a method like this.$emit('fromHeader', { //somevalue }. Now, here's my question: if main.vue is used as the layout ...

Exploring the process of web scraping from dynamic websites using C#

I am attempting to extract data from using HtmlAgilityPack. The website is dynamic in nature, displaying content after the page has fully loaded. Currently, my code retrieves the HTML of the loading bar using this method, but encounters a TargetInvocation ...

Having trouble getting the expected transition effects to work with Vue.js

Currently, I have a display of lists of items through the use of v-for. Initially, only the summary section of each item is visible. Upon clicking on an item, the details section is supposed to appear. This functionality is achieved by adding or removing ...

How can I position an element at the bottom of a page using VueJS and Bootstrap CSS?

https://i.sstatic.net/ojanG.png I am trying to move my footer (Copyright statement) to the bottom of the page. However, it is creating some extra white space beneath the footer. How can I eliminate this additional white space? This issue is occurring in ...

Use jQuery or javascript to eliminate the 'Webpage Dialog' from the 'showModalDialog' window

At one point on the page, I have a line of code that looks like this: onclick="window.showModalDialog("http://rauf-thecoder.blogspot.com/");" When executed, it displays the following: Is there a way to eliminate the title bar text for the Webpage Dialog ...

What is the process for customizing the appearance of a prop within the <TextField> component?

Using my custom DatePicker.js component, I have two instances of <TextField>. When the user clicks on the <CalendarIcon> within the <TextField>, a small calendar pops up. However, I want to style the label in the <TextField> in a sp ...

Display text when hovered over or clicked to insert into an HTML table

I have an HTML table connected with a component field gameArray and I need it to: Show 'H' when the user's cursor hovers over TD (:hover) and the corresponding field in gameArray is an empty string, Fill the gameArray field after a click. ...