Javascript 使用 AJAX 初始化 Vue 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32413905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initializing Vue data with AJAX
提问by muttley91
I'm trying to populate a Vue with data from the JsonResult
of an AJAX query. My Vue receives the data just fine when I encode it from my View Model, but not when I try to retrieve it using AJAX. Here's what my code looks like:
我正在尝试使用来自JsonResult
AJAX 查询的数据填充 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>
This is with all of the proper includes. I know that @Url.Action("GetItems", "Settings")
returns the correct URL and the data comes back as expected (as tested by an alert in the success function (see comment in success function in AJAX). Populating it like so: var allItems = @Html.Raw(Json.Encode(Model));
works, but the AJAX query does not. Am I doing something wrong?
这是所有适当的包含。我知道@Url.Action("GetItems", "Settings")
返回正确的 URL 并且数据按预期返回(通过成功函数中的警报测试(参见 AJAX 中的成功函数中的注释)。像这样填充它:var allItems = @Html.Raw(Json.Encode(Model));
有效,但 AJAX 查询没有。我是做错了什么?
回答by Samuel De Backer
You can make the ajax call inside of the mounted function (“ready” in Vuejs 1.x).
您可以在挂载的函数内进行 ajax 调用(Vuejs 1.x 中的“就绪”)。
<script type="text/javascript">
var ItemsVue = new Vue({
el: '#Itemlist',
data: {
items: []
},
mounted: function () {
var self = this;
$.ajax({
url: '/items',
method: 'GET',
success: function (data) {
self.items = JSON.parse(data);
},
error: function (error) {
console.log(error);
}
});
}
});
</script>
<div id="Itemlist">
<table class="table">
<tr>
<th>Item</th>
<th>Year</th>
</tr>
<tr v-for="item in items">
<td>{{item.DisplayName}}</td>
<td>{{item.Year}}</td>
</tr>
</table>
</div>
回答by muttley91
I was able to solve my problem by performing my necessary action within the success handler on the AJAX call. You can either put the entire Vue object creation in there, or just set the data you need.
我能够通过在 AJAX 调用的成功处理程序中执行必要的操作来解决我的问题。您可以将整个 Vue 对象创建放在那里,也可以只设置您需要的数据。
回答by hoogw
I had same problem, fixed by Samuel De Backer's answer above.
我有同样的问题,由上面 Samuel De Backer 的回答解决。
The problem is at ajax success callback function,
问题在于ajax成功回调函数,
if you use this.data, it is incorrect, because when 'this' reference the vue-app, you could use this.data, but here (ajax success callback function), this does not reference to vue-app, instead 'this' reference to whatever who called this function(ajax call).
如果使用this.data,则不正确,因为'this'引用vue-app时,可以使用this.data,但是这里(ajax成功回调函数),this并没有引用vue-app,而是'this ' 引用任何调用此函数的人(ajax 调用)。
So you have to set var self = this before ajax, then pass into callback function (success call back)
所以你必须在ajax之前设置var self = this,然后传入回调函数(成功回调)
Here is my working code
这是我的工作代码
created () {
this.initialize()
},
mounted () {
this.getData()
},
methods: {
getData() {
var getUser_url = url + 'cfc/sw.cfc?method=getUser&returnformat=json&queryformat=struct';
console.log(getUser_url )
/*
You can use a plethora of options for doing Ajax calls such as Axios, vue-resource or better yet the browser's built in fetch API in modern browsers.
You can also use jQuery via $.ajax() API, which simply wraps the XHR object in a simple to use method call
but it's not recommended to include the whole jQuery library for the sake of using one method.
http://updates.html5rocks.com/2015/03/introduction-to-fetch
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses.
It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
*/
// ********** must use self = this **************
// this reference vue-app. must pass it to self, then pass into callback function (success call back)
var self = this;
fetch(getUser_url).then(function (response) {
return response.json();
}).then(function (result) {
console.log(result);
// must use self.user, do not use this.user,
// because here, this's scope is just the function (result).
// we need this reference to vue-app,
self.user = result; // [{}, {}, {}]
}); // fetch(){}
console.log(this.user);
},
initialize () {}