【发布时间】:2016-07-29 01:45:47
【问题描述】:
我遇到了一个奇怪的问题,即在 Vue DevTools 中找到的值是正确的。它按预期在我的数据中声明。当我第一次点击“编辑”一个项目时,正确的值也会显示在我的浏览器窗口中。
但是,如果我单击“编辑”一个具有不同数量的项目,即使它不正确(它应该从数据库中预先填充),也会再次显示相同的值。
然后,如果我再次单击第一个“编辑”项,该值将更新为之前的值!
最疯狂的部分是,虽然我的浏览器窗口没有显示正确的值,Vue DevTools 中始终显示正确的结果!下图中带圆圈的项目是“数量”100 的 UUID,这是正确的值。然而 700 出现了(前一个 Edit 项的值)。有没有人曾经发生过这种情况并知道是什么原因?
这是一些相关代码的 sn-ps(它来自使用 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>
【问题讨论】:
-
您是否使用像
bootstrap-select或类似的选择插件?如果是这样,您可能需要在以编程方式设置新值后调用.refresh()之类的方法来更新 UI 以显示新选择。 -
我认为我们可能需要更多代码来解决这个问题。示例数据库响应,选择框的代码会有所帮助。此外,最好在
data选项中预先定义可用值,即。Quantity键如果要与v-model一起使用,则应该立即具有值 -
@Jeff 我添加了更多 HTML。数量不用作 v 模型。如您所见,DB 响应很好,因为它一直到 Vue DevTools 都可以。
-
@DelightedD0D 是的,很好的观察 - 我正在使用 selected-select 并且正在使用一个名为 v-chosen 的 vue 指令,它应该会有所帮助。我也会在上面添加该指令。
-
@DelightedD0D 添加了更多代码
标签: javascript jquery laravel vue.js vue-resource