3

How do I import globally with Vue 3 in the main.js the ref, reactive and computed?

I'm trying to avoid doing this in each component:

import { ref, reactive, computed } from 'vue'
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Adri HM
  • 2,314
  • 2
  • 17
  • 30

2 Answers2

3

Not sure this is a good idea (it likely defeats tree shaking), but it's possible to make them global by adding them to window:

// main.js
import { ref, reactive, computed } from 'vue'

window.ref = ref
window.reactive = reactive
window.computed = computed

If using ESLint, make sure to configure these globals:

// eslintrc.js
module.exports = {
  globals: {
    ref: true,
    reactive: true,
    computed: true,
  }
}
tony19
  • 125,647
  • 18
  • 229
  • 307
  • I think this is a really bad idea and (as @tony19 himself says) it shouldn't be encouraged. It makes the functions global to the browser, but in Vue3, "global" doesn't mean "global-to-the-browser"; it means global to the Vue Application. `ref`, `computed`, etc. should be appended to the Application object, not the window object, and it would still be accessible at the top-level in your Vue Components. To any junior Devs coming across this thread, don't start doing this! Other answers and comments on this thread point to more elegant solutions. – cartbeforehorse Jan 06 '23 at 17:04
1
npm i vue-global-api
// main.js
import 'vue-global-api'

https://www.npmjs.com/package/vue-global-api

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 08 '22 at 11:47