user101289 user101289 - 4 months ago 41
Ajax Question

vue.js updating different model from form select

I've got a dynamic select list created with

vue.js
. I want to update a "details" box on the page with data grabbed via an
ajax
call. The basic idea is here: https://jsfiddle.net/pznej8dz/1/

I don't see why the
sf_detail
data isn't being updated when the object is updated from the webservice call. Is there a different way this should be done in vue?

Answer

Your object references are getting out of sync! Calling getSourceFieldDetails causes field and sf_detail to reference different objects.

The Problem

At the start of the script, an object is created

{
  Name: 'Test',
  Label: 'Data',
  Type: 'Boolean'
};

And that object is given a reference named sf_detail.

In sf_detail_info, field is set equal to the reference named sf_detail

data: {
  field: sf_detail
}

But, in getSourceFieldDetails, sf_detail is set to reference a new object. Thus sf_detail references the new object, but field still references the old one.

The Solution

The simplest solution is to never set sf_detail equal to a new object. Instead, update the properties of the existing object. The modified version of getSourceFieldDetails looks like this:

function getSourceFieldDetails(val) {
  // this would actually call an ajax endpoint to get this data
  console.log(val[0]);
  sf_detail.Name = val[0];
  sf_detail.Label = val[0] + 'Label',
  sf_detail.Type = val[0] + 'DataType'
  console.dir(sf_detail);
}

Here is a fork of your fiddle with the change.

Comments