关于vue3:Vue3-设置全局变量

形式一:

  • main.js 设置全局变量

    import api from '@/api'
    
    app.config.globalProperties.$api = api
  • 应用全局变量,应用 getCurrentInstance 办法。

    // ctx.$api 就是全局设置的变量
    const {
    proxy: { $api },
    } = getCurrentInstance();
    
    // ctx.$api 就是全局设置的变量
    const { ctx } = getCurrentInstance();

    形式二:

  • vue3新的 provide/inject 性能能够穿透多层组件,实现数据从父组件传递到子组件。
  • 能够将全局变量放在根组件的 provide 中,这样所有的组件都能应用到这个变量。
  • 如果须要变量是响应式的,就须要在 provide 的时候应用 ref 或者 reactive 包装变量。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理