Assigning objects in Vue.js methods

I am working on a Vue component where I need to select a specific value from an array of objects and then copy certain fields from that value into Vue data.

  <div class="container">
    <h4>Add Item</h4>
    <form @submit.prevent="addItem(item.Code)">
      <div class="row">
        <div class="col-md-6">
          <div class="form-group">
            <label for="ItemCode">Code</label>&nbsp;
            <select
              id="ItemCode"
              v-model="item.Code"
            >
              <input
                v-model="item.Code"
                type="hidden"
              >
              <option
                v-for="part in PartCodes"
                :key="part"
              >
                {{ part }}
              </option>
            </select>
   .
   .
   .
    </form>
  </div>

Here is the data structure:

  data() {
    return {
      item: {},
      parts: [],
    };
  },
  computed: {
    PartCodes: function () {
      return [...new Set(this.parts.map(p => p.Code))];
    },
  },
  created() {
    let uri = '/parts';
    if (process.env.NODE_ENV !== 'production') {
      uri = 'http://localhost:4000/parts';
    }
    this.axios.get(uri).then(response => {
      this.parts = response.data;
    });
  },
  methods: {
    addItem(selectCode) {
      let uri = '/items/create';
      if (process.env.NODE_ENV !== 'production') {
        uri = 'http://localhost:4000/items/create';
      }
      let selectPart = this.parts.filter( obj => {
        return obj.Code === selectCode;
      });

      this.item.Description = selectPart.Description;
      this.item.Cost = selectPart.Cost;
      this.item.Price = selectPart.Price);

      this.axios.post(uri, this.item)
        .then(() => {
          this.$router.push({name: 'QuoteIndex'});
        });
    }
  }
};

Although the object 'selectPart' logs the correct fields, assigning these fields to the 'item' object results in 'undefined' values.

I believe I am facing a scope issue, but I am unsure of what exactly is causing the problem.

Any suggestions on how to properly copy fields within this Component would be greatly appreciated.

Thank you. https://i.sstatic.net/ESjUf.png

Answer №1

Within Vue 2.x, it is important to note that properties added to objects are not reactive. When declaring the item data item, if the properties Description and Price are not initially included and are later assigned through a simple object assignment, Vue will not be able to track these changes.

To address this issue, there are two solutions:

1. Declare all reactive properties upfront

Modify the data method like this:

data() {
    return {
      item: {
        Description: null,
        Price: null
      },
      parts: [],
    };
  },

2. Use Vue.set()

Change the code from:

this.item.Description = selectPart.Description;
this.item.Price = selectPart.Price;

to:

this.$set(this.item, 'Description', selectPart.Description);
this.$set(this.item, 'Price', selectPart.Price);

Fortunately, it has been announced that Vue 3.x will eliminate this caveat, making all properties added to reactive objects reactive themselves.

Answer №2

Presented below is a refined solution to tackle the issue at hand.

Suggested replacement: Consider using .find() instead of .filter()

  <div class="content">
    <h3>Insert New Item</h3>
    <form @submit.prevent="addItem(item.Code)">
      <div class="row">
        <div class="col-md-6">
          <div class="form-group">
            <label for="ItemCode">Code</label>&nbsp;
            <select
              id="ItemCode"
              v-model="item.Code"
            >
              <input
                v-model="item.Code"
                type="hidden"
              >
              <option
                v-for="part in PartCodes"
                :key="part"
              >
                {{ part }}
              </option>
            </select>
   .
   .
   .
    </form>
  </div>

Representation of the data is as follows:

  data() {
    return {
      item: {          
          Code: null,
          Description: null,
          Group: null,
          GroupCount: null,
          Quantity: null,
          ExtQuantity: null,
          Cost: null,
          Price: null,
          QuoteNumber: null},
      parts: [],
    };
  },
  computed: {
    PartCodes: function () {
      return [...new Set(this.parts.map(p => p.Code))];
    },
  },
  created() {
    let uri = '/parts';
    if (process.env.NODE_ENV !== 'production') {
      uri = 'http://localhost:4000/parts';
    }
    this.axios.get(uri).then(response => {
      this.parts = response.data;
    });
  },
  methods: {
    addItem(selectCode) {
      let uri = '/items/create';
      if (process.env.NODE_ENV !== 'production') {
        uri = 'http://localhost:4000/items/create';
      }
      let selectPart = this.parts.find( obj => {
        return obj.Code === selectCode;
      });

      this.item.Description = selectPart.Description;
      this.item.Cost = selectPart.Cost;
      this.item.Price = selectPar.Price;

      this.axios.post(uri, this.item)
        .then(() => {
          this.$router.push({name: 'QuoteIndex'});
        });
    }
  }
};

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 rendering of the input dropdown control in Angular JS is experiencing difficulties

I am currently using your Angular JS Input Dropdown control, and I have followed the code example provided on your demo page in order to implement the control on a specific page of my website built with PHP Laravel. However, I have encountered an issue dur ...

Creating a JSON Response Using PHP API

I created a basic JSON response to test the functionality of an AJAX request on a mobile device. Using a local domain called test.local, I generated a json response. header("Content-Type:application/json; charset=utf-8"); echo json_encode(array('nam ...

The CSP header is configured incorrectly, please correct it

Having trouble with my website's JavaScript. The dropdown box in Bootstrap isn't working on the main page, but works fine in a sub-directory. My CSP header is: script-src 'self' //ajax.cloudflare.com According to the CSP documentation ...

The attempt to remove a cookie through a Next.js server-side operation was unsuccessful

Having trouble removing a cookie using the next/headers module in my Next.js application. The code snippet below is what I've tried: import {cookies} from "next/headers"; export default async function Signout() { async function deleteTok ...

Ways to increase the number of rows on datatables while utilizing ajax integration

My issue lies in trying to implement pageLength for my datatables using ajax. Instead of displaying 50 table rows per page as expected, it shows the entire dataset on each page. Here is the code snippet I am working with: JS $('table.dataTableAjax&ap ...

Issues with reading response headers in AngularJS when using Apiary.IO?

I am attempting to mock my API using Apiary.io, but I am facing an issue where I cannot retrieve any headers from the response object in angularJS. I have verified that at least Content-Type: application/json is correctly set up by checking in firebug. The ...

Issue with npm version: 'find_dp0' is not a valid command

Hello, I have a small node application and encountered an issue while running a test. The error message displayed is as follows: 'find_dp0' is not recognized as an internal or external command, operable program or batch file. It seems to be re ...

Unable to successfully import Node, JS, or Electron library into Angular Typescript module despite numerous attempts

I'm still getting the hang of using stack overflow, so please forgive me if my question isn't formulated correctly. I've been doing a lot of research on both stack overflow and Google, but I can't seem to figure out how to import Electr ...

I'm encountering an issue with my API Key being undefined, despite having it saved in both an .env file and as a global variable

While attempting to retrieve information from an API, I encountered an issue where the key I was using was labeled as "undefined". However, after manually replacing {key=undefined} with the correct string in the network console, I was able to successfull ...

Exploring arrays with JavaScript and reading objects within them

Recently, I received assistance from a member of StackOverflow regarding AJAX calls. However, I have encountered a problem now. The code consists of a loop that sends requests to multiple REST APIs and saves the results in an array as objects. The issue ...

Is it possible to group an array of objects by a specific element?

Take a look at this example: JsFiddle Query: I'm dealing with the following JSON Array y= [ {"LngTrend":15,"DblValue":10,"DtmStamp":1358226000000}, {"LngTrend":16,"DblValue":92,"DtmStamp":1358226000000}, {"LngTrend":17,"DblValue":45,"DtmSta ...

Can you explain the distinctions among “assert”, “expect”, and “should” in the Chai framework?

Can you explain the variations between assert, expect, and should? How do you know when to utilize each one? assert.equal(3, '3', '== turns values into strings'); var foo = 'bar'; expect(foo).to.equal('bar' ...

unable to retrieve JSON sub-elements

I encountered an issue while attempting to iterate through the JSON object provided. When trying to access the content-items using page.content-items, I received an error message. Is it possible to access an object that has a key with "-" in its name? Co ...

Is it advisable to combine ng-change with ng-blur in AngularJS?

Seeking clarification on the correct usage of AngularJS's ng-change and ng-blur from an expert. Specifically, when updating a form value. In the code snippet below, I have a dropdown where I would like to trigger overrideBusinessDec() when the user ...

Customizing the JavaScript Calendar in Qualtrics

I came across a JavaScript code snippet that allows you to embed a calendar into a Qualtrics question. Specify a date for the survey: <link href="https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css" rel="stylesheet" type="text/css" /> <script sr ...

Setting up Eslint Airbnb with VScode in a Vue project for optimal code formatting and style enforcement

This is my Vue.js code without proper linting. https://i.sstatic.net/TjiWz.png After running npm run lint --fix The code now looks like this https://i.sstatic.net/o1kUm.png However, when I make changes and press Control + C, it reverts back to the ...

Unable to supersede CSS module styling using global or external stylesheets in React, Next.js, or React Native

I'm facing a challenge finding a solution to a basic issue. I have a component that is initially styled using a class from a *.module.css file. However, I want to replace this style with one from a global stylesheet or another stylesheet but I can&apo ...

What is the process for converting a multidimensional array from PHP into JavaScript?

Recently, I've been experimenting with dygraph. To populate my graph, I fetch data via an ajax call and then need to convert the returned JSON array into a JavaScript array. My dygraph options are set up like this: series = { sample1: { ...

Obtain the final array within an array composed of multiple arrays

My dilemma involves working with a dynamically generated array, where I need to extract only the values from the last array for aggregation purposes, discarding all others. Imagine a structure similar to this: let target = [] let data = [ [ { name: &apo ...

Create a JavaScript function that continues to execute even after a button has been clicked

Although it may seem like simple logic, I am currently unable to log in. Imagine I have a function called mytimer() stored in a common file that is linked to every HTML page. mytimer(){...........................}; Now, at some point on another page, whe ...