Vue3.0 怎么挂载全局属性和安装插件?

vue3.0 通过createApp创建的入口,已经没有把Vue对象暴露出来。
之前的通过给prototype挂载全局属性和通过use安装插件的方式用不了。
vue3.0的实现方式应该是怎么样的?

1 Like

乱写了一个,只是use的时候始终都不会提示 AxiosRequestConfig ,有点蛋疼。

import {
  App,
  inject,
  Plugin
} from 'vue'

import axios, {
  AxiosInstance,
  AxiosRequestConfig
} from 'axios'

const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'

const PolySymbol = (name: string) =>
  hasSymbol
    ? Symbol('[vue-axios]: ' + name)
    : ('[vue-axios]: ') + name

const VueAxiosKey = PolySymbol('vue-axios')

const VueAxios: Plugin = {
  install<AxiosRequestConfig> (app: App, config?: AxiosRequestConfig) {
    const $axios = axios.create(config)
    app.config.globalProperties.$axios = $axios

    app.provide(VueAxiosKey, $axios)
  }
}

function useVueAxios (): AxiosInstance {
  return inject(VueAxiosKey) as AxiosInstance
}

export {
  useVueAxios
}

export default VueAxios

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $axios: AxiosInstance
  }

  interface App {
    use(plugin: Plugin, config?: AxiosRequestConfig): this
  }
}
1 Like

这是在main.js中挂载vant3.0的示例代码,可以参考下

import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import Vant from 'vant';
import 'vant/lib/index.css';

createApp(App).use(Vant).mount('#app')
1 Like

const vue = createApp(App);
vue.component(YInput.name, YInput);
vue.use(store).use(router).mount(’#app’);

全局属性
app.config.globalProperties.foo = ‘bar’