【发布时间】:2015-12-01 13:08:43
【问题描述】:
我正在尝试使用来自 AJAX 查询的 JsonResult 的数据填充 Vue。当我从我的视图模型对数据进行编码时,我的 Vue 可以很好地接收数据,但当我尝试使用 AJAX 检索数据时却没有。这是我的代码的样子:
<script type="text/javascript">
var allItems;// = @Html.Raw(Json.Encode(Model));
$.ajax({
url: '@Url.Action("GetItems", "Settings")',
method: 'GET',
success: function (data) {
allItems = data;
//alert(JSON.stringify(data));
},
error: function (error) {
alert(JSON.stringify(error));
}
});
var ItemsVue = new Vue({
el: '#Itemlist',
data: {
Items: allItems
},
methods: {
},
ready: function () {
}
});
</script>
<div id="Itemlist">
<table class="table">
<tr>
<th>Item</th>
<th>Year</th>
<th></th>
</tr>
<tr v-repeat="Item: Items">
<td>{{Item.DisplayName}}</td>
<td>{{Item.Year}}</td>
<td></td>
</tr>
</table>
</div>
这是所有正确的包含。我知道@Url.Action("GetItems", "Settings") 返回正确的 URL 并且数据按预期返回(由成功函数中的警报测试(请参阅 AJAX 中成功函数中的注释)。像这样填充它:var allItems = @Html.Raw(Json.Encode(Model)); 有效,但是 AJAX查询没有。我做错了吗?
【问题讨论】:
-
您必须在收到数据后更新视图的数据项。请注意,该 ajax 是异步的(因此得名),因此您只会在
success回调函数中拥有数据! -
我该怎么做?我不能做 ItemsVue.data.Items 对吗?我不确定当时如何更新它......
-
我想我可以在
success回调函数中创建我的Vue! -
对不起,我不知道vue.js的API,所以帮不上忙。在快速查看参考后,我建议尝试:
ItemsVue.$data.items=datainsidesuccess回调。 -
如果你在
successcallback 中创建它,你只需要先在全局范围内定义它
标签: javascript jquery ajax asp.net-mvc vue.js