Ahm*_*aki 8 javascript ajax vue.js vue-resource vuejs2
有一种情况我必须mounted在vuejs中的第一个ajax(在函数中)之后得到额外的数据,我已经把第二个ajax置于第一个ajax的if条件和内部success函数中!
它工作正常,我在Vue Devtools中看到chrome中的数据,但数据不会在视图中呈现.
伪代码:
var vm = new Vue({
el: '#messages',
data: {
participants: [],
active_conversation: '',
messages: []
},
methods: {
getParticipants: function () {
return this.$http.post('message/get-participants').then(
function (response) {
vm.participants = response.data.participants;
// if there is a conversation_id param in url
if (getUrlParameterByName('conversation_id')) {
// Second Ajax Is Called Here inside First Ajax
return vm.getConversationMessages (getUrlParameterByName('conversation_id')); // this ajax call is getting data but not showing in view
}
}
},
getConversationMessages : function(conv_id){
// Second Ajax Call to get Conversation messages
// and showing them , works onClick
return this.$http.post('message/get-messages/' + conv_id).then(
function (response) {
if (response.data.status == 'success') {
console.log(response.data.messages)
vm.messages = response.data.messages;
vm.$forceUpdate();
}
},
mounted: function () {
this.getParticipants()
}
})
Run Code Online (Sandbox Code Playgroud)
获取特定会话消息的第二个Ajax调用是响应onclick事件并显示消息,但是当在First Ajax成功响应(getParticipants())中使用此函数时,它正确获取数据我可以在DevTools VueJs Extension中看到消息已设置但是视图没有显示消息,我尝试过 vm.$set()但没有机会.
更新:
第二个Ajax正在处理没有错误和消息数据属性被填充(我检查了Vue DevTools),唯一的问题是视图没有显示消息!但是当我通过点击一个对话手动完成它,第二个ajax再次执行,我可以看到消息!,我也尝试vm.$forceUpdate()了第二个ajax后没有机会.
Update2 html部分(错误就在这里!!)
<a vbind:id="conv.id" v-on:click="getMessages(conv.id)" onclick="$('#user-messages').addClass('active')">
Run Code Online (Sandbox Code Playgroud)
getConversationMessages当您仅使用 ajax 请求而不将其放入
getConversationMessagesajax 请求的成功回调中时,DOM 会使用消息进行更新,getParticipants因为这一行遇到了错误
this.participants = response.data.participants;
Run Code Online (Sandbox Code Playgroud)
您在 ajax 请求的成功回调中使用普通函数,这就是this没有指向 vue 实例的原因,并且this.participants会给您一个未定义的错误。因此,请使用vminstead 指向 vue 实例,就像在程序的其余部分中所做的那样
vm.participants = response.data.participants;
Run Code Online (Sandbox Code Playgroud)
编辑
var vm = new Vue({
el: '#messages',
data: {
participants: [],
active_conversation: '',
messages: []
},
methods: {
getParticipants: function () {
return this.$http.post('message/get-participants');
},
getConversationMessages : function(conv_id){
return this.$http.post('message/get-messages/' + conv_id);
}
},
mounted: function () {
this.getParticipants().then(function (response){
vm.participants = response.data.participants;
if (getUrlParameterByName('conversation_id')) {
return vm.getConversationMessages (getUrlParameterByName('conversation_id')); // this ajax call is getting data but not showing in view
}
}).then(function(response){
if (response.data.status == 'success') {
console.log(response.data.messages)
vm.messages = response.data.messages;
});
}
})
Run Code Online (Sandbox Code Playgroud)