Implementing Vuejs Array Push in Separate Components

I am attempting to extract data from an object and store it in an array using Vue. My goal is to have each value stored in a separate array every time I click on an item. Each click should push the todo into a different array. How can I achieve this separation for pushing into different arrays?

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript"},
      { text: "Learn Vue"},
      { text: "Play around in JSFiddle"},
      { text: "Build something awesome"}
    ],
    mytodo:[]
  },
  methods: {
  myClickTodo: function(e){
    this.mytodo.push(e.target.innerText) 
    console.log(e.target.innerText)
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <h2>My list One:</h2>
  <ul>
    <li v-for="todo in todos" @click="myClickTodo">
      {{ todo.text + " from todo one" }}
    </li>
  </ul>

  <p>todo 1 </p>
  <p>{{mytodo}}</p>

<hr>

<h2>My list Two:</h2>
  <ul>
    <li v-for="todo in todos" @click="myClickTodo">
      {{ todo.text + " from todo two" }}
    </li>
  </ul>


  <p>todo 2</p>
  <p>{{mytodo}}</p>
</div>

Answer №1

Quick and Effective Solution

To quickly resolve the issue, consider converting mytodos into a double array structure (one for each TODO list):

data() {
  return {
    mytodo: [[], []]
  };
}

Next, make sure to update your event handler (click) to send the specific array element of mytodos along with the todo item you want to add:

<!-- List One -->
<li v-for="todo in todos" @click="myClickTodo(mytodos[0], todo)">

<!-- List Two -->
<li v-for="todo in todos" @click="myClickTodo(mytodos[1], todo)">

Additionally, adjust the myClickTodo method to handle these new parameters accordingly:

methods: {
  myClickTodo(mytodo, todo) {
    mytodo.push(todo.text);
  }
}

(Additional Vue.js code snippets can be found within the original content. The solution revolves around encapsulating the TODO lists into reusable components for enhanced modularity.)

Enhanced Component Approach

An alternative approach involves encapsulating the TODO lists within a modular component known as "my-list":

Vue.component('my-list', {
  data: () => ({
    title: '',
    mytodo: [],
  }),
  props: {
    todos: {
      type: Array,
      default: () => []
    }
  },
  template: `<div>
    <h2>{{title}}</h2>
      <ul>
        <li v-for="todo in todos" @click="myClickTodo(mytodo, todo)">
          {{ todo.text + " from todo one" }}
        </li>
      </ul>

      <p>{{mytodo}}</p>
    </div>`,
  methods: {
    myClickTodo(mytodo, todo) {
      mytodo.push(todo.text);
      console.log(todo.text);
    }
  }
});

This more advanced setup permits simplified use of the app template:

<my-list title="List One:" :todos="todos"></my-list>
<my-list title="List Two:" :todos="todos"></my-list>

(Further scripting details are available in the initial example. Opting for components enhances versatility and maintainability in the application development process.)

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

"Enhance your website with captivating Javascript hover effects for

Can anyone assist me with incorporating the navigation hover effect seen on this website into my HTML/CSS project? The example site is built using a WordPress theme, but I am looking to apply that green effect to my own webpage and have the ability to cust ...

Having trouble navigating the Request and Response handling in Expressjs/Nodejs?

As I continue to delve deeper into this code, confusion seems to cloud my understanding. Here is the provided source: var express = require('express') , http = require('http') , server = express() ; var home = require('./ro ...

Can a Javascript function parameter be transferred to PHP?

As I understand it, PHP is used on the server-side and JavaScript is used on the client-side. However, I am curious if there is a way to achieve the following scenario. Imagine having a JavaScript function that makes an Ajax call to a PHP file. Here is an ...

Updating the progress state of MUI linear determinate diligently

I currently have a modal set up that handles some asynchronous logic for submitting data to a database. The component I am using, called LinearDeterminate, is designed using Material-UI. You can find more information about it here: MUI Progress import { u ...

Having trouble with the authorization aspect of Next Auth. The error message reads: "NextAuth.js does not support the action api with HTTP GET method

Recently, I've been encountering a puzzling error with my Next.js app authentication. It seems that I am unable to authenticate with the provided credentials. After reviewing the documentation, everything appears to be correct on my end. Additionall ...

What is causing the discrepancy in functionality between these two HTML/CSS files with identical code?

In this codepen, you'll find the first example: Subpar Pen: https://codepen.io/anon/pen/jGpxrp Additionally, here is the code for the second example: Excellent Pen: https://codepen.io/anon/pen/QqBmWK?editors=1100 I'm puzzled why the buttons l ...

How to effectively utilize multiple Vue instances in your project?

My inquiry is somewhat linked to a similar question on Stack Overflow, but I am uncertain about the level of discouragement towards the approach discussed in relation to Vue. In my situation, I am working on a project where the DOM is generated entirely b ...

Retrieving the text or value of an ASP.NET label using JavaScript

One of my challenges is transferring a string of data from C# to JavaScript in ASP web forms. My plan involves setting the data as a text for an ASP label in C#, then extracting the label's text by ID in JS. This is the C# code (ascx.cs file): L ...

JavaScript function executes before receiving AJAX response

Within my code, there is an AJAX function named flagIt() that gets triggered by another function called validateForm() upon submission. The validateForm() function is responsible for form validation. function validateForm(){ var error = ""; //perf ...

What is the best way to incorporate an apostrophe into a string so that it can be displayed in a tooltip using jQuery

There is a text or string stored inside the 'data' variable, containing some texts with apostrophes. The issue I'm facing is that the tool tip is not displaying the text after the apostrophe symbol. How can I include all texts, including apo ...

Introducing Vuetify 3's v-file-input with interactive clickable chips!

I noticed an unexpected issue with the v-file-input component in Vuetify3. In Vuetify 2, it was possible to use the selection slot to customize the display of selected files. This functionality still works in both versions, as mentioned in the documentatio ...

JS: delay onClick function execution until a page refresh occurs

Currently, I am working on a WordPress site that involves a form submission process. Upon successful submission, a new post is created. After the user submits the form, I have implemented JavaScript to prompt them to share a tweet with dynamically prepopu ...

Troubleshooting Angular 2 with TypeScript: Issue with view not refreshing after variable is updated in response handler

I encountered a problem in my Angular 2 project using TypeScript that I could use some help with. I am making a request to an API and receiving a token successfully. In my response handler, I am checking for errors and displaying them to the user. Oddly en ...

Implementing a Javascript solution to eliminate the # from a URL for seamless operation without #

I am currently using the pagepiling jQuery plugin for sliding pages with anchors and it is functioning perfectly. However, I would like to have it run without displaying the '#' in the URL when clicking on a link like this: www.mysite.com/#aboutm ...

Display a tooltip on v-autocomplete dropdown elements in Vuetify version 2.x

Seeking help with vuetify 2.x - I'm looking for a way to display tooltips for each item in the drop-down menu of v-autocomplete. The drop-down menu includes checkboxes and text fields. <v-autocomplete solo :items="..." v-model="sele ...

Dealing with click events on layers with z-index positioning

In the map application I am developing, I have implemented 2 z-index layers. However, a problem arises when attempting to zoom in by clicking on these layers. The click handler is located on the lower z-index layer and I do not want it to execute when a co ...

Is the value incorrect when using angular's ng-repeat?

Currently iterating through an array nested within an array of objects like this: <div ng-repeat="benefit in oe.oeBenefits"> <div class="oeInfo" style="clear: both;"> <div class="col-md-2 oeCol"> <img style="he ...

Issue with handling keypress event and click event in Internet Explorer

Below is the HTML code for an input text box and a button: <div id="sender" onKeyUp="keypressed(event);"> Your message: <input type="text" name="msg" size="70" id="msg" /> <button onClick="doWork();">Send</button> </di ...

I am currently working on an Electron Project and am interested in incorporating vueJS into it

I'm working on an Electron Project and I'm unable to incorporate vuejs into it. Can someone guide me on how to use vuejs in an Electron Project? Do I need to install vue cli and electron separately? ...

Maintaining Flexbox layout without triggering item re-rendering for a new container

This is the unique layout I'm aiming to create: I am facing a challenging flexbox layout that needs to be implemented. One of the items in this layout is a Webgl player, which cannot be conditionally rendered due to the restarting issue it may cause. ...