How can you access the index of an object in Vue.js when one of its properties has been modified

Here's the Vue component code I'm working with:

data: function () {
    return {   
        products: [ 
            { product_id: '', price: ''}, 
            { product_id: '', price: ''},  
        ],
    }
},

I am looking for a solution to get the object index when the v-model="product_id" is changed. Is there any way to achieve this?

<div v-for="(product, key) in products">
    <input type="text" v-model="product.product_id" />
    <input type="text" v-model="product.price" />
</div><!--  /.div -->

Any help will be greatly appreciated. Thank you!

Answer №1

Instead of complicating things, why not just include a method that triggers when the @change event occurs?

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: 'Learn JavaScript' },
      { text: 'Learn Vue' },
      { text: 'Play around in JSFiddle' },
      { text: 'Build something awesome' }
    ]
  },
  methods: {
    getIndex(index) {
    console.log(index)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-for="(todo, index) in todos" @key="index">
    <input type="text" v-model="todo.text" @change="getIndex(index)">
  </div>
</div>

Answer №2

Check out this resource: findIndex

data() {
    return {
    items: {  
            item_list: [ 
                { id: '1', cost: '50'}, 
                { id: '2', cost: '93'},  
            ],
            additional_field: '',
    },
  }
},
watch: {
    'items.item_list.id'(newId) {
    this.items.additional_field = this.items.item_list.findIndex(item => item.id == newId)
  }
}

Answer №3

One way to implement this functionality is by using a watch function in Vue.js:

watch: {
   'products.product': {
       handler(newValue, oldValue) {
           // Check if the value has changed
           if(newValue != oldValue) {
              // Identify the row that was modified
              let [rowChanged] = _.difference(newValue, oldValue);
              // Find the index of the modified row
              let arrayIndex = newValue.indexOf(rowChanged);
           }  
       },
       deep: true
   }
}

This code snippet demonstrates how to achieve the desired behavior. Additionally, you can consolidate all your code into a jsfiddle for better visualization of the entire .vue component.

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 Discord.js .cleanContent attribute does not show up when using Object.keys() and cannot be logged

My Discord.js Message object should contain a property called .cleanContent, according to the documentation, and it should be a string. console.log(message.cleanContent) works correctly, but console.log(message) does not display the cleanContent propert ...

Using JQuery to eliminate the current div in an image slider

I currently have an image slider that allows users to switch between images. There are two buttons - one adds a new item to the slider, while the other is supposed to remove the current image from the slider, but it doesn't seem to be working properly ...

Securely encoding information with PHP and decrypting it using JavaScript

I'm currently working with 2 servers. My goal is to generate a pair of keys, store the private key in local storage, and send the public key to my PHP server. The main objective is to encrypt data using the public key in PHP and decrypt it using Jav ...

Incorporating additional rows into a SQL Table according to user-provided information

My application features editable table rows using Vue, which pull data from a database. Currently, there is a button (add line) that inserts a row into the database when clicked. Is it possible to automatically add a specified number of lines based on user ...

Using Router.back in Next.js triggers a complete page refresh

I am working on a page called pages/conversations/[id].tsx, and here is the code: import Router, { useRouter } from 'next/router' export default function ConversationPage() { const router = useRouter() ... return ( <View ...

Getting data from an Array using Axios in Laravel

After making an Axios request to one of my controller functions, it retrieves all the suppliers' information from the database. However, when this data is returned to my VUE file, there seems to be no data present. Here is the Axios request: mounted ...

Utilizing Axios for Vue Multiselect on select/enter Event

I have successfully implemented a Vue Multiselect feature that retrieves options from my database using an axios call. This functionality works great as it allows users to select existing options or add new ones to create tags. While this setup is working ...

What could be the reason for this JavaScript malfunctioning in both Chrome and Safari browsers?

Why is it that the javascript works fine in Firefox for the gallery on the page below, but doesn't seem to be functioning properly in Chrome and Safari? In Chrome, the big image isn't displaying but the thumbnails are, and in Safari nothing show ...

Calculating the average value of an attribute in an array using Mongodb (Mongoose)

Seeking assistance with a query to find sellers near users based on location input and sorting them by average rating. Is this achievable? Snippet of the model including an array of reviews: const sellerSchema = new mongoose.Schema({ _id: Mongo ...

Prevent onClick event in jQuery and extract parameters from a function call

We've been tasked with implementing a temporary solution to some code, so it might seem a bit silly at first. But please bear with us. The goal is to block the onclick method of an anchor tag, extract the parameters from the function call, and then u ...

Unable to connect to node.js webserver using the godaddy shared hosting URL

Upon entering www.example.com:3000 into my browser, I am encountering the following error message (where 'example' represents my domain name) This site can't be reached - www.example.com took too long to respond. I have taken the following ...

The React hamburger menu triggers a re-render of child elements within the layout

I am currently working with React and Material UI v5. Within my layout, I have a menu component with children. Whenever I click on the menu, it triggers a refresh of the children components. I attempted to resolve this by encapsulating the child components ...

Utilizing THREE.JS Raycaster with JavaScript "entities" rather than just meshes

I am facing a challenge with the Raycaster model. I grasp the concept of how it intersects meshes that can be transformed, but my issue lies in identifying when the specific instance of an object is clicked. Consider a scenario where there is a button. Th ...

Struggling with implementing Angular and TypeScript in this particular method

I'm dealing with a code snippet that looks like this: myMethod(data: any, layerId: string, dataSubstrings): void { someObject.on('click', function(e) { this.api.getSomething(a).subscribe((result: any) => { // ERROR CALL 1. It ...

What is the best way to store and retrieve data from the current webpage using HTML, CSS, and JavaScript?

Is there a way to persistently save the button created by the user even when the browser is refreshed? Here is an example code snippet: function create(){ const a = document.createElement("button") document.body.appendChild(a) const b = documen ...

Guide to modifying the root directory when deploying a Typescript cloud function from a monorepo using cloud build

Within my monorepo, I have a folder containing Typescript cloud functions that I want to deploy using GCP cloud build. Unfortunately, it appears that cloud build is unable to locate the package.json file within this specific folder. It seems to be expectin ...

Discover the process for finding a Youtube Channel Name with querySelectorAll

OUTPUT : Console URL : https://www.youtube.com/feed/trending?gl=IN document.querySelectorAll('a[class="yt-simple-endpoint style-scope yt-formatted-string"]')[0].innerText; document.querySelectorAll('a[class="yt-simple-endpoi ...

Allow AngularJS to make HTTP POST requests with CORS enabled

I am looking to submit a form to send an HTTP POST request to a server located on a different domain, with CORS enabled in the server script using Node.js. Below is the Angular configuration script: var myApp = angular.module('myApp', ['ng ...

Troubleshooting issues with custom global components failing to apply styling in NuxtJs

I have designed various components such as buttons that I want to be able to use and reuse across my entire website. I have already developed plugins Object.entries(components).forEach((([name, component]) => { Vue.component(name, component) })) and ...

What is the best way to send AJAX post data to a Node.js server?

I am currently facing an issue with passing a unique ID object back to the server side using Ajax after making an API call. I need help figuring out what might be going wrong in my code. This is the client side code snippet where I loop through a JavaScri ...