且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Vue 3 中使用 Vue.prototype 或全局变量?

更新时间:2023-11-25 08:11:58

您可以使用 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."