如何在 Vue 3 中使用 Vue.prototype 或全局变量? [英] How to use Vue.prototype or global variable in Vue 3?

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

问题描述

和标题一样,我想在Vue原型中加入Axios.所以当我想使用的时候,可以像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, {}>>'.

我该如何解决这个问题?

How could I fix this problem?

推荐答案

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

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(...)
}

选项 API:

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

2.全局配置 (用于选项 API)

2. Global config (for Options API)

import axios from 'axios';

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

选项 API:

this.$axios

注意:这仅适用于 Options API.Evan You(Vue 创建者):"config.globalProperties 旨在作为复制 Vue.prototype 行为的逃生舱口.在setup 函数中,只需导入您需要的内容或显式使用provide/inject 将属性公开给应用程序.上>

Note: This is only for the Options API. Evan You (Vue creator) says: "config.globalProperties are meant as an escape hatch for replicating the behavior of Vue.prototype. In setup functions, simply import what you need or explicitly use provide/inject to expose properties to app."

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆