Vue.prototype 全局方法不起作用?

我在main.js里面写了如下代码:

Vue.prototype.$handleOrgQuery = function (property) {
  let org = sessionStorage.getItem("userOrgs");
  if (org) {
    console.log('--- org ---', org)
  }
}

image.png

阅读 7.5k
2 个回答

写错了项目,尴尬

以axios为例定义全局变量


vue2

import axios from 'axios'
Vue.prototype.$axios = axios

使用this.$axios.xxx


vue3-global-api

Vue.prototype Replaced by config.globalProperties
import axios from 'axios';

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

使用this.$axios.xxx

vue3-provide/inject

Provide

import axios from 'axios';

const app = Vue.createApp(App);
app.provide('$axios', axios); 

Inject

Composition API:

const { inject } = Vue;
...
setup() {
  const $axios = inject('$axios');   
  // $axios.get(...)
}

Options API:

inject: ['$axios'],
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题