1

When working with Vue.js, the biggest problem I have faced is declaring a global function that can be used anywhere in the Vue application without any import.

I have tried Vue plugin. Custom Vue plugin's function can only be used in templates. It seems that it's not possible to use in the setup script tag.

How to declare a global function that can be used anywhere in the application without import?

James Z
  • 12,209
  • 10
  • 24
  • 44
Efthakhar Bin
  • 21
  • 1
  • 3
  • 1
    By simple search in Vue docs you could find this https://vuejs.org/api/application.html#app-config-globalproperties – Boussadjra Brahim Apr 15 '23 at 22:10
  • Can you show me how you access global property in vue js 3 script setup tag in composition api?? – Efthakhar Bin Apr 15 '23 at 22:23
  • A clean way is to use import. See https://stackoverflow.com/questions/10525582/why-are-global-variables-considered-bad-practice . Third-party tools like https://github.com/antfu/unplugin-vue-components do imports implicit, but it's a hack – Estus Flask Apr 15 '23 at 22:28
  • @EstusFlask Thanks for your first link. I have point out why vue does not provide enough flexibility for global variable. – Efthakhar Bin Apr 15 '23 at 22:43
  • @EstusFlask, I'm surprised you describe unplugin's technique as a *"hack"*. Could you elaborate? – tao Apr 16 '23 at 00:25
  • @EfthakharBin It's not really a job for a framework. Vue does this for templates because they go through a compiler and use internal instance that has "global" properties. This isn't the case for script block. If a variable isn't there. This is a job for build tool or you, depending on your case. There's ProvidePlugin in Webpack (Vue CLI) and `@rollup/plugin-inject` for Rollup (Vite). You can declare global vars on `window` but it's much less desirable for the reasons explained in that link – Estus Flask Apr 16 '23 at 08:08
  • 1
    @tao It's non-spec compliant, so you write not JS but something else, and it can cause any kind of problems with the tools that rely on normal behaviour. Same for Vue SFC, but the problem with niche things like unplugin is that it relies on community plugins supported by single devs and not teams or companies. If it stops being maintained, this hurts your project, the risk isn't worth it, this happened to me more that I can afford. Most problems related to global vars are still applicable with unplugin, you'll have hard time to track and untangle dependencies if you have to. – Estus Flask Apr 16 '23 at 08:21

0 Answers0