简体   繁体   中英

Setting VueJS model property doesn't update select element in DOM

I have a cascading dropdown using VueJS (1.0), and I'm having a problem where a change in the Vue model isn't being reflected in the DOM.

The elements in the dropdown need to be an object, but once selected I'm trying to change the value of the property/dropdown to an int.

I'm doing this with a watch event, which processes the necessary information from the object, then uses $set on the property to set it to the required int.

Using the VueJS Chrome dev tools, I can see the change reflected on the component's property, but when submitting the form it's POSTed as the string [object Object] , as if the DOM was never updated.

Here is the relevant dropdown in the template:

<select :disabled="releases.length &lt; 1" v-model="release" options="releases" class="form-control input-sm" name="{{formname}}[release_id]">
    <option selected="selected" value="">Choose Release...</option>
    <option v-for="obj in releases" v-bind:value="obj">{{obj.text}}</option>
</select>

And here is the watch event:

"release": function() {
   this.$parent.$data.promos = this.release.promos;
   this.$set('release', this.release.id);
}

After changing the dropdown, the root promos property is updated, and according to dev tools the release property of the component is correctly set to the id

开发工具截图

But when the form is submitted, I just get the string representation of the object!

POST截图

Does anyone know what I'm doing wrong here; or is this a VueJS bug/is there a workaround?

Thank you!

The value attribute of an option can be tied to an object in Vue, but the browser still needs to render the value as valid HTML so the object is cast to a string.

One thing you can do is add a hidden field to the form with a value set to the ID of the selected release object.


Edit : Another option could be overriding the toString method of the class prototype to return the ID of the object.

I will not be able to find the bug in your code unless I can play around with it in jsFiddle or equivalent.

But I have an alternate implementation of cascading dropdown for you here: https://jsfiddle.net/mani04/Lgxrcc5p/1/

You may see if that provides any pointers. This example uses Vue 2.0.3

In your code sample above, I specifically do not understand this part:

<select :disabled="releases.length &lt; 1" ...

Is that a copy-paste error? I hope you have the following code in your editor:

<select :disabled="releases.length < 1" ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM