【发布时间】:2021-08-24 14:27:00
【问题描述】:
我正在使用打字稿在 Nuxtjs 应用程序中工作,并且我为 Axios 创建了一个自定义插件,该插件将一些函数注入到上下文中。我可以使用商店中的这些功能(它有效),但是,即使我收到一个错误,告诉我我正在使用的属性在类型商店中不存在。这样做的正确方法是什么?有什么必须要做的配置吗?
这是插件axios.js的代码
export default function ({ $axios, redirect }, inject) {
$axios.onResponse((response) => {
if (response.data == null)
console.log(`Undefined or null data from url ${response.config.url}`)
})
$axios.onError((error) => {
const code = parseInt(error.response && error.response.status)
console.log('REQUEST ERROR')
console.log('ENDPOINT:',error.request?.responseURL);
if(error.response)
console.log(error.response.data)
else
console.log("SIN DATOS")
if (code === 404) {
redirect('/404')
}
})
const request = async (
method = 'get',
path,
data = {},
params = {}
) => {
const config = {
headers: {
'Content-Type': 'application/json'
},
method: method,
url: $axios.defaults.baseURL + path,
data: data,
params: params
}
return $axios(config)
}
const get = (path,params) => request(undefined,path,undefined,params)
const post = (path, data) => request('post',path,data)
const customAxios = {
get,
post
}
// Inject to context as $customAxios
inject('customAxios', customAxios)
}
这是我使用插件 user.ts 的一小部分代码
//ACTIONS
export const actions: ActionTree<RootState, RootState> = {
setPhoneLink({ commit }, setPhoneLink: string) {
commit('setPhoneLink', setPhoneLink)
},
setHasSameAddressOfId({ commit }, sethasSameAddressOfId: boolean) {
commit('setHasSameAddressOfId', sethasSameAddressOfId)
},
async login({ commit }, loginBody: LoginBody) {
return this.$customAxios
.post('seguridad/login/web/', loginBody)
.then((response: any) => {
console.log('RESPONSE OF LOGIN:', response.data)
commit('setUserData', response.data)
})
},
这是我得到的错误
ERROR in store/user.ts:229:17
TS2339: Property '$customAxios' does not exist on type 'Store<any>'.
227 | },
228 | async login({ commit }, loginBody: LoginBody) {
> 229 | return this.$customAxios
| ^^^^^^^^^^^^
230 | .post('seguridad/login/web/', loginBody)
231 | .then((response: any) => {
232 | console.log('RESPONSE OF LOGIN:', response.data)
【问题讨论】:
标签: typescript vue.js nuxt.js vuex