本文介绍了如何在Vue 3中使用Vue.prototype或全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像标题一样,我想将Axios添加到Vue原型中.因此,当我要使用它时,可以像 this.$ axios 这样使用它,而不必每次都导入它.

Like the title, I want to add Axios into Vue prototype. So when I want to use it, I can use it like this.$axios instead of importing it every time.

代码:

//plugins/axios.ts

import axios from 'axios'
import router from '../router/index'

const errorHandle = (): void => {};

const instance = axios.create({
  // baseURL: process.env.NODE_ENV == 'development' ? '' : ''
  baseURL: 'http://localhost:3000',
  timeout: 1000 * 12
});

instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

export default instance
import { createApp } from 'vue'
import App from './App.vue'
import installElementPlus from './plugins/element'
import instance from './plugins/axios'
import router from './router'

const app = createApp(App).use(router)
installElementPlus(app)
// app.config.globalProperties.http = instance
app.config.globalProperties.$axios= instance
app.mount('#app')

但是,当我尝试像这样使用它时出现问题: this.$ axios .

However, there is a problem when I try to use it like this: this.$axios.

TS2339: Property '$axios' does not exist on type 'ComponentPublicInstance<{}, {}, {}, {}, {}, EmitsOptions, {}, {}, false, ComponentOptionsBase<{}, {}, {}, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, EmitsOptions, string, {}>>'.

我该如何解决此问题?

推荐答案

您可以使用 provide / inject 或定义一个全局配置属性,以替换 VueVue 3中的.prototype :

You could use provide/inject or define a global config property, which replaces Vue.prototype in Vue 3:

提供

import axios from 'axios';

const app = Vue.createApp(App);
app.provide('$axios', axios);  // Providing to all components during app creation

注入

合成API:

const { inject } = Vue;
...
setup() {
  const $axios = inject('$axios');   // injecting in a component that wants it
  // $axios.get(...)
}

Options API:

inject: ['$axios'],   // injecting in a component that wants it

2.全局配置(用于Option API)

2. Global config (for Options API)

import axios from 'axios';

const app = Vue.createApp(App);
app.config.globalProperties.$axios = axios;

Options API:

this.$axios

这篇关于如何在Vue 3中使用Vue.prototype或全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 06:29