0👍
Since Vue 3 has introduced the composition API, there is no this
keyword available in the setup
function. So, there is no use in binding functions or variables into Vue.prototype
or app.config.globalProperties
to share common functionalities across the app globally. But, defining global components works properly.
import { createApp } from 'vue'
import { App } from './App.vue'
import MyComponent from './components/MyComponent.vue'
let app = createApp(App)
// Register global components
app.component('MyComponent', MyComponent);
app.mount('#app')
To define global functions (using mixins or plugins), you should use the Options
interface instead. All Vue 2 exercises are available in the v3 Options interface, too.
// Register global functions
app.config.globalProperties.$MyFunction = () => console.log('my custom fn');
Later you can use the $MyFunction
in your Vue options API component:
<template>
<my-component/>
</template>
<script>
export default {
mounted() {
this.$MyFunction();
}
}
</script>
It turned out, the composition API is more readable, maintainable, and scalable than the old Options API. All dependencies that a component or a composable function relies on, are obvious by looking at the imports.
In this case, if you want to reduce the import lines, you can re-export composition functions in index.js
of the root directory.
src
-- composable
---- index.js
---- use-comp-1.js
---- use-comp-2.js
-- pages
---- HomePage.vue
// src/composable/use-comp-1.js
export function useComp1() {
return 1;
}
// src/composable/use-comp-2.js
export function useComp2() {
return 2;
}
// src/composable/index.js
export { useComp1 } from 'src/composable/use-comp-1';
export { useComp2 } from 'src/composable/use-comp-2';
// HomePage.Vue
<script setup>
import { useComp1, useComp2 } from 'src/composable';
const a1 = useComp1();
const a2 = useComp2();
</script>
Summary
In absence of the this
keyword in the setup function, using global functions is not possible. On the other hand, composition API provides a better way of writing maintainable codes.