I'm struggling to figure out the best method for updating data properties in Vue. Computed properties and watchers aren't getting the job done. What

I'm facing a challenge with updating certain input fields on a form I'm currently working on. After receiving data from axios in one data property, I am attempting to prefill some fields with the response. There are four fields returned from the server that I want to maintain similar v-model bindings on the inputs for easy submission of two prefilled fields along with the rest of the form data.

Initially, I tried using a watcher on the data upon retrieval, but it didn't yield any results. Now, I have implemented a computed method aiming to update my data properties once Axios fetches a response.

data() {
  pluResponse: {},
  item: {
    plu: '',
    commodity: '',
  },
},

handlePLUInput(event) {
  axios.post(API_SEARCH_ENDPOINT,
    this.item,
    { headers: {
        'Content-type' : 'application/json',
     }
     }).then(response => {
       this.pluResponse = response.data.data[0];
     }).catch(error => {console.log(error)};
},

computed: {
  item(pluResponse) {
    this.item.plu = pluResponse.plu;
    this.item.commodity = pluResponse.commodity;
  }
}

Although no error messages are being displayed, the item data property simply doesn't appear to update. could it be that the Computed method isn't triggering?

Answer №1

One potential solution would be to handle PLU input in the following way:

handlePLUInput(event) {
  axios.post(API_SEARCH_ENDPOINT,
    this.item,
    { headers: {
        'Content-type' : 'application/json',
     }
     }).then(response => {
       this.pluResponse = response.data.data[0];
       this.item.plu = this.pluResponse.plu;
       this.item.commodity = this.pluResponse.commodity;
     }).catch(error => {console.log(error)};
},

Answer №2

First and foremost, computed properties must always have a defined value. This means that any method within the computed section should return a value.

Moreover, it is not recommended to create side effects in methods that calculate computed property values, such as altering a data property. You can read more about this concept here.

Lastly, it appears that having a computed property with the same name as a data property is likely causing the issue you are facing. This conflict could be the root of your problem.

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

Unsupported Media Type: 415 Error during MultipartFile Upload

When trying to upload a file using spring boot and vue, I encountered an error '415 : Unsupported MediaType'. This is the snippet of my spring boot controller. @PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}, produces = {MediaType. ...

What is the process for accessing getBoundingClientRect within the Vue Composition API?

While I understand that in Vue we can access template refs to use getBoundingClientRect() with the options API like this: const rect = this.$refs.image.$el.getBoundingClientRect(); I am now attempting to achieve the same using template refs within the com ...

Guide on adding checkboxes for each child component in a Vue ads table

<vue-ads-table :columns="fields" :rows="items" :selectable="true" @row-selected="onRowSelected" class="my-table" ...

Passing Parameters Using Axios in Vue.js

Currently, I am utilizing Axios within VueJS to make ajax requests. However, I have encountered an issue when attempting to send these requests. This snippet shows my JavaScript code: axios.post('http://localhost/app/php/search.php', { quer ...

Setting a const variable back to its original value in VueJS

Is there a way to reset the constant variable value in Vue? Here's what I have: data(){ const _hdrList = [ { label: 'start_time', value: 'start_time' }, { la ...

Issue encountered when integrating vue2-google-maps into a project using vue.js and Laravel 5.6.12

I am currently utilizing Laravel 5.6.12 in combination with vue.js I am attempting to integrate Google Maps using the following GitHub link I am adhering to the instructions provided in the aforementioned link, as follows. Installation npm install vue2 ...

The reactivity of Vuex store properties is lost when they are newly created

Currently, I am utilizing Vue.js and Quasar, along with a Vuex store. Although the properties that were initially present during the initialization of the store are reactive, none of the newly created properties on an object of the store seem to be reacti ...

What is the best way to showcase the proper layout of my article, created using a WYSIWYG editor, with the help of Vue.js and Laravel

Can anyone provide guidance on how to display a customized article from a WYSIWYG editor using Vue.js? In Laravel, I am accustomed to using {!! $article->content !!} to show the full content. How can I achieve the same result in Vue.js using {{article ...

Guide on accessing a nested array within a JSON object using JavaScript

I'm currently faced with a json object that contains nested arrays and names with spaces like Account ID. My goal is to only display the Account ID's within my Vue.js application. While I can access the entire response.data json object, I'm ...

Is Vue instance created if element is present?

I am currently developing an application where some pages contain Vue instances, while others do not. My issue arises when switching from one page to another, and the following warning message appears: [Vue warn]: Cannot find element: #element-id How can ...

Vuelidate - The Key to Ensuring Error-Free Logic in Validation

Explore the official example of vuetify's form validation (using vuelidate) with this code snippet: <v-text-field v-model="name" :error-messages="nameErrors" :counter="10" label="Name" required @input="$v.name.$touch()" @blur="$v.nam ...

How can I include npm package js and css files in Vue CLI with webpack?

I am currently attempting to integrate an npm package into my vue-cli development site. The instructions provided by the package website are as follows: https://i.stack.imgur.com/R2Inl.png The instructions state that both the css and js files need to be ...

An interface display within a network router

My current project involves an authentication system and a backend dashboard. By default, the route displays the authentication component: { path: "/", name: "Authentication", component: Auth }, Once logged in, I am redirected to another Vue compon ...

Determine if the user has liked the post using VUEJS

I need to verify whether the user has already liked the post. I have an array containing the users who have liked the post, but I'm unsure how to hide the button if the logged in username is present in the likes array. Here's the relevant code sn ...

State in React is not always defined when making a fetch request

Just started using React and encountered an issue while working on my fetch request: I am receiving a formatted response with Axios, but when I try to set the state using the same variable like this: setSelectedStatParams(formattedResponse), it shows up as ...

Unable to figure out a method to properly synchronize a vue.js asynchronous function

I am facing an issue with my code where everything works fine if I uncomment the "return" statement in fetchData. How can I make sure that I wait for the completion of this.fetchData before populating the items array? I have tried using promises, async/awa ...

Problem with Vue app deployment in a subdirectory arises when the route changes from the specified publicPath

We are faced with a dilemma in our Vue application deployment to a subdirectory known as /deploypath/ Presently, our vue.config.js file looks like this: const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ publi ...

Warning message will appear before navigating away from the page if vee-validate is

Wondering how to create a simple confirmation prompt asking if the user really wants to leave a page that includes a basic HTML form. The HTML Form: <!DOCTYPE html> <html> <head></head> <body> <div id="app"> ...

Horizontal alignment of buttons within a textfield in Vuetify 2

I'm currently working with vuetify 2 and I am attempting to create a unique text field that includes 2 or more buttons as an inner append. I recently came across a snippet showcasing something similar here: https://www.reddit.com/r/vuetifyjs/comments/ ...

The process of incorporating external JavaScript scripts into VueJS Components

I currently have two external scripts that need to be used for the payment gateways. At the moment, both scripts are placed in the index.html file. However, I prefer not to load these files at the beginning of the process. The payment gateway is only re ...