ajax 호출을 수행 하기 위해 자체 호출 함수 를 사용하려고합니다 . 나중에 응답을 사용하여 Vue 내부의 데이터 속성을 채우고 싶지만 어떤 이유로 그렇게 할 수 없습니다.
지금까지 내 코드는 다음과 같습니다.
//chiamata Ajax a servizio
var getData = (function(){
var req = $.ajax({
type:'get',
url:'https://api.myjson.com/bins/a8ohr',
dataType: 'json',
success: function(response)
{
result =JSON.parse(response);
}
});
return {
getResponse:function(){
return req.success;
}
}
}());
var modello = getData.getResponse();
내 목표는 modello
Vue에서 데이터 로 전달 하는 것입니다 .
여기 VUE :
var Metromappa = new Vue({
el: '#metromappa',
data: {
modello:modello
},
methods:{
},
beforeMount(){
this.modello = modello;
}
})
내가 뭘 잘못 했어?
대신 created()
라이프 사이클 후크 에서 ajax 호출을 수행하고 다음과 같이 응답에 대한 데이터 속성 modello 를 설정할 수 있습니다 .
var Metromappa = new Vue({
el: '#metromappa',
data: {
modello:null
},
methods:{
},
created(){
var self = this;
$.ajax({
type:'get',
url:'https://api.myjson.com/bins/a8ohr',
dataType: 'json',
success: function(response){
self.modello = response;
}
});
},
})
다음은 jsFiddle입니다.
논리를 분리하려는 경우 :
var getData = function(){
return $.ajax({
type:'get',
url:'https://api.myjson.com/bins/a8ohr',
dataType: 'json',
success: function(response){
console.log(response);
}
});
};
var Metromappa = new Vue({
el: '#metromappa',
data: {
modello:null
},
methods:{
},
beforeMount(){
var self = this;
getData().then(function(response){
self.modello = response;
}, function(error){});
}
})
내 실수를 지적 해준 Bert Evans에게 감사합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다