Use Vue Composition API globally
Instead of import APIs from vue
in every file,
import { ref, computed, watch } from 'vue'
const counter = ref(0)
const doubled = computed(() => counter.value * 2)
watch(doubled, (v) => {
console.log('New value: ' + v)
})
Now you can directly use them everywhere (with TypeScript support!)
const counter = ref(0)
const doubled = computed(() => counter.value * 2)
watch(doubled, (v) => {
console.log('New value: ' + v)
})
npm i vue-global-api
Then import vue-global-api
in your main entry to register the global apis
// main.js
import 'vue-global-api'
And enjoy :)
By default, importing vue-global-api
will register 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'
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?
MIT License © 2021 Anthony Fu