我有一个奇怪的问题,在 Vue DevTools 中找到的值是正确的。它按预期在我的数据中声明。第一次单击“编辑”项目时,正确的值也会显示在我的浏览器窗口中。
但是,如果我单击“编辑”一个具有不同数量的项目,即使它不正确(它应该从数据库中预填充)也会再次显示相同的值。
然后,如果我再次单击第一个“编辑”项,该值将更新为以前的值!
最疯狂的部分是,虽然我的浏览器窗口没有显示正确的值,但正确的结果始终显示在 Vue DevTools 中!下图中带圆圈的项目是“数量”100 的 UUID,这是正确的值。然而 700 出现了(前一个编辑项的值)。有人曾经发生过这种情况并知道是什么原因吗?
这是一些相关代码的片段(它来自使用 vue-resource 的 Vue 组件,这是在 Laravel 项目的引导模式中发生的):
Vue JS
data() {
return {
selected_options: {},
attributes: [],
}
},
methods: {
editLineItem: function (line_item) {
this.getProductOptionsWithAttributes(line_item.product_id);
this.getPrepopulatedOptionsForLineItem(line_item.id);
},
getProductOptionsWithAttributes: function (product_id) {
var local_this = this;
var url = '/api/v1/products/' + product_id + '/options';
this.$http.get(url).then(function (response) {
local_this.attributes.$set(0, response.data);
}, function (response) {
// error handling
});
},
getPrepopulatedOptionsForLineItem: function (id) {
var local_this = this;
var url = '/api/v1/line_items/' + id + '/options';
this.$http.get(url).then(function (response) {
Object.keys(response.data).forEach(function (key) {
Vue.set(local_this.selected_options, key, response.data[key]);
});
}, function (response) {
//@TODO Implement error handling.
});
},
}
HTML
<div v-for="(key, attribute) in attributes[0]" class="col-md-12 selectbox_spacing">
<label for="option_{{$index}}">{{key}}</label><br/>
<select class="chosen-select form-control" v-model="selected_options[key]" v-chosen="selected_options[key]" id="option_{{$index}}">
<option v-for="option in attribute" value="{{option.id}}">{{option.name}}</option>
</select>
</div>
<button v-on:click="editLineItem(line_item)">
Main.js vue 指令:
Vue.directive('chosen', {
twoWay: true, // note the two-way binding
bind: function () {
$(this.el)
.change(function(ev) {
// two-way set
//this.set(this.el.value);
var i, len, option, ref;
var values = [];
ref = this.el.selectedOptions;
if(this.el.multiple){
for (i = 0, len = ref.length; i < len; i++) {
option = ref[i];
values.push(option.value)
}
this.set(values);
} else {
this.set(ref[0].value);
}
}.bind(this));
},
update: function(nv, ov) {
// note that we have to notify chosen about update
$(this.el).trigger("chosen:updated");
}
});
var vm = new Vue({
el : '#wrapper',
components: {
LineItemComponent
}
});
edit.blade.php 文件中的脚本:
<script>
$(document).ready(function() {
$('#lineItemModal').on('shown.bs.modal', function () {
$('.chosen-select', this).chosen('destroy').chosen();
});
}
</script>