首页 > 解决方案 > Vue.prototype.$property 不适用于 Typescript

问题描述

在 main.ts 中:

Vue.prototype.$http = http

然后在另一个组件中,在我无法调用的类中this.$http。我已经阅读了有关增强类型的信息,但不知道在哪里放置文件,如何调用它,关于这个主题的文档不是很清楚:https://vuejs.org/v2/guide/typescript。 html#Augmenting-Types-for-Use-with-Plugins

所以我创建了一个文件'src/types/vue.d.ts':

import Vue from 'vue'
import http from '@/http'

declare module 'vue/types/vue' {
  interface Vue {
    $http: http
  }
}

http.ts 的内容:

import axios from 'axios'

const HTTP = axios.create({
  baseURL: process.env.VUE_APP_API_URL
})

export default {
  login(credentials: any) {
    return HTTP.post('/auth', {
      account_email: credentials.email,
      account_password: credentials.password
    })
  }
}

但我仍然不能this.$http在组件中使用。我的目标是this.$http在每个组件中全局使用对 http.ts (此处为 axios 模块)的引用。

标签: typescriptvue.js

解决方案


Vue 3 答案

增强 Vue 以支持您的自定义组件属性是通过模块扩充完成的。要添加您的$http声明并支持它,您可以创建vue-shim.d.ts文件并扩充vue/runtime-core

import axios from 'axios'

declare module '@vue/runtime-core' {
  export interface ComponentCustomProperties {
    $http: typeof axios
  }
}

Vue 还断言,对于版本 3,您必须将其导入或导出为文件中的顶级代码行,ts以确保将其视为模块:

确保声明文件是 TypeScript 模块 为了利用模块扩充,您需要确保文件中至少有一个顶级导入或导出,即使它只是 export {}。

现在,当您安装自定义插件时,您可以将其挂在app.config.globalProperties对象上:

// my-custom-plugin.js
import axios from 'axios'
import http from 'plugins/http'

export default {
  install (app, options) {
    app.config.globalProperties.$http = http
  }
}

有关 Vue 2 的答案,请参见下文。

Vue 2 答案

您不能将 的类型声明$http为值,而是进行新的输入:

// http.d.ts

export default interface {
  login(credentials: any): PromiseLike<any> 
}

然后将其用作您的打字声明:

import http from '@/types/http'

...
interface Vue {
  $http: http
}

现在http.ts按照上面评论中的链接进行操作:

import _Vue from 'vue'
import axios from 'axios'

const http = {
  login(credentials: any) {
    return HTTP.post('/auth', {
      account_email: credentials.email,
      account_password: credentials.password
    })
  }
}

export function http(Vue: typeof _Vue): void {
  Vue.prototype.$http = http;
}        

现在您需要导入该http.ts文件并将Vue.use其导入main.ts

import Http from '@/http'

Vue.use(Http)

现在您的组件可以使用您的 http 插件:

mounted() {
  this.$http.login(credentials)
  .then((response) => console.log(response))
  .catch((error) => console.warn(error))
}

推荐阅读