首页 > 解决方案 > 如何使用 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)

标签: typescriptvue.jsnuxt.jsvuex

解决方案


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
  }
}

推荐阅读