且构网

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

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

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

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

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

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."