typescript - 如何使用 Nuxt 将插件功能注入 Vuex 商店而不会出现 Typescript 错误?
问题描述
我正在使用打字稿在 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)
解决方案
Store<S>
是 Vuex 中定义的类型,因此您需要通过在其中注入自定义插件来扩展它。
您可以创建使用自定义 axios 实例vuex.d.ts
声明的文件,如下所示:Store<S>
import type { NuxtAxiosInstance } from '@nuxtjs/axios'
declare module 'vuex/types/index' {
interface Store<S> {
$customAxios: NuxtAxiosInstance
}
}
推荐阅读
- c - 如何使用 json-c 转换几个 JSON 对象?
- reactjs - 安全性:我可以在本地更改(例如在 chrome 中).env 变量、react 状态或 redux 状态吗?
- ios - Unity 2019.3.7f1 ios 未构建
- c++ - 为什么 C++20 不支持“void f(Concept const auto&)”?
- java - 在 Spring Boot 中使用 hibernate-types-52 时如何禁用 Hypersistence 横幅?
- python-3.x - python(熊猫)中的嵌套Excel数据透视表
- r - R:错误:自动绘图不支持数字类型的对象
- javascript - React JS 状态值不会在下一个函数调用中立即更新
- python - 具有内部类的计数器实例方法
- javascript - User.find 不是函数,编译后无法覆盖“用户”模型