Инициализация данных Vue с помощью AJAX
Я пытаюсь заполнить Vue данными из JsonResult
запроса AJAX. Мой 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 запрос не делает. Я что-то делаю неправильно?
Ответы
Ответ 1
Вы можете сделать вызов 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>
Ответ 2
Мне удалось решить мою проблему, выполнив необходимые действия в обработчике успеха при вызове AJAX. Вы можете либо разместить здесь весь объект Vue, либо просто установить нужные вам данные.
Ответ 3
У меня была та же проблема, исправленная ответом Сэмюэля де Бакера выше.
Проблема в функции обратного вызова AJAX,
если вы используете this.data, это неверно, потому что, когда 'this' ссылается на vue-app, вы можете использовать this.data, но здесь (функция обратного вызова ajax success), это не ссылается на vue-app, вместо этого 'this 'ссылка на того, кто вызывал эту функцию (вызов ajax).
Поэтому вы должны установить var self = this перед ajax, а затем перейти в функцию обратного вызова (успешный обратный вызов)
Вот мой рабочий код
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 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 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 scope is just the function (result).
// we need this reference to vue-app,
self.user = result; // [{}, {}, {}]
}); // fetch(){}
console.log(this.user);
},
initialize () {}
Ответ 4
Есть и другой способ:
new Vue({
el:"#app",
data:{
populateByAjax:{}
},
beforeCompile: function() {
this.getRequestByAjax();
},
methods:{
getRequestByAjax:function(){
var xhr = new XMLHttpRequest();
var args = "action=lol";
var self = this;
xhr.open('POST', './filephp', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onready = function (aEvt) {
if(xhr.readyState == 4 && xhr.status==200) {
self.populateByAjax = JSON.parse(xhr.responseText);
console.log(self.populateByAjax);
}
}
xhr.send(args);
}
}
И не забудьте закончить свой *.php файл:
echo json_encode($result);
Ответ 5
Вам лучше использовать
$( "#Itemlist" ).load( yourUrl, function() {
alert( "Load was performed." );
});
Подробнее здесь