✨ Try unplugin-auto-import
, a compile time successor of this package. Providing a lot more flexibility and tree-shaking support!
Use Vue Composition API globally
Instead of import APIs from vue
in every file,
<script setup>
import { ref, computed, watch } from 'vue'
const counter = ref(0)
const doubled = computed(() => counter.value * 2)
watch(doubled, (v) => {
console.log('New value: ' + v)
})
</script>
Now you can directly use them everywhere (with TypeScript support!)
<script setup>
const counter = ref(0)
const doubled = computed(() => counter.value * 2)
watch(doubled, (v) => {
console.log('New value: ' + v)
})
</script>
npm i vue-global-api
Then import vue-global-api
in your main entry to register the global apis before any usages
// main.js
import 'vue-global-api'
And enjoy :)
Powered by
vue-demi
, this package also works for Vue 2.
By default, importing vue-global-api
will register all common composition apis to the global object. If you want to have fine-grain control, use submodule per API:
// only register `ref` and `computed` as global APIs
import 'vue-global-api/ref'
import 'vue-global-api/computed'
We have provided a few sub-set collections if you want to control the global API registration by their type.
// register all reactivity apis (`ref`, `computed`, `watch`, etc.)
import 'vue-global-api/reactivity'
// register all lifecycle hooks (`onMounted`, `onUpdated`, `onUnmounted`, etc.)
import 'vue-global-api/lifecycle'
// register component apis (`inject`, `provide`, `h`, etc.)
import 'vue-global-api/component'
If you want to have global api work in CDN, you don't actually need this package. All you need to do is:
Object.assign(window, Vue)
In the latest <script setup>
, compile time macros like defineProps
and defineEmits
are now available globally without the need to import them from vue
. So, as your components are likely to rely on composition APIs like ref
and computed
, why don't we just have them available globally as well?
If you use ESLint it'll complain about you using undefined variables. This package provides the ESLint config presets to solve it.
Extend in your ESLint config:
// .eslintrc.js
module.exports = {
extends: [
'vue-global-api'
]
};
It also provides the same collections and single API options for fine-grain control.
// .eslintrc.js
module.exports = {
extends: [
// collections
'vue-global-api/reactivity',
'vue-global-api/lifecycle',
'vue-global-api/component',
// single apis
'vue-global-api/ref',
'vue-global-api/toRef',
]
};
MIT License © 2021 Anthony Fu