【发布时间】:2018-07-22 22:24:32
【问题描述】:
我正在使用前端的 Vue 和后端的 Django Rest Framework 来重建我的网站。由于所有 AJAX 调用的身份验证/标头/错误处理将是相同的,我认为我应该将其放在某个共享文件中。所以我创建了一个 fetchPlugin.js 来处理这个问题,并将它插入到我的 Vue 实例中 $fetch 下。
要发布通知,我使用的是vue-notification,只需调用$notify,我就可以在任何地方发布通知。除了我的$fetch 插件。在我的插件中提取的回调函数内部,当我像Vue.prototype.$notify 一样使用它时,调用确实有效。但直接在函数内部却没有。在此处查看我的注释代码:
let fetchPlugin = {}
fetchPlugin.install = function(Vue, options){
Vue.prototype.$fetch = {
get(url, processingFunction, show_loading=false, extra_options={}){
if(show_loading){
// This call does not work
Vue.prototype.$notify({
group: 'loading',
title: 'Loading...',
type: 'success'
})
}
let default_options = {
credentials: 'same-origin',
}
options = Object.assign(default_options, extra_options)
fetch(url, options)
.then(function(response){
if(show_loading){
// This call works
Vue.prototype.$notify({
group: 'loading',
clean: true
})
}
if(!response.ok){ throw response }
return response.json()
})
.then(processingFunction)
.catch(err => {
console.log(err)
// This call also works
Vue.prototype.$notify({
group: 'fetch',
title: 'An error occurred',
type: 'error'
})
})
}
}
}
export default fetchPlugin
在我的main.js 中,我在fetchPlugin 之前导入和使用vue-notification,所以我想我可以访问vue-notification 添加的$notify 函数。由于在设置期间还没有 Vue 实例可供参考:
Vue.use(Notification)
Vue.use(fetchPlugin)
但显然这并不像我预期的那样有效。为什么访问$notify 可以在.then 函数内部工作,但不能在它们外部工作?如何让加载通知正常工作?
更新:我已通过 console.log(Vue.prototype) 验证 $notify 存在于 fetch 回调函数和我的插件的 get 函数的开头。否则它当然也会在我脸上抛出一些异常。那么问题来了,如果函数调用正确并且没有发生异常,为什么不会弹出通知?
【问题讨论】:
标签: javascript vue.js vuejs2