If you simply want to substitute {{ appName }}
in any template with 'Vue 3'
(string) without importing anything, the most efficient approach would be utilizing config.globalProperties, as recommended by others:
const app = createApp(App).mount('#app');
app.config.globalProperties.appName = 'Vue 3'
However, it's important to exercise caution when using this method excessively. It contradicts the principles of reusability and modularization that underlie the Composition API.
The primary reason for avoiding excessive use of globalProperties
is that it acts as a shared property field across Vue3 applications, potentially leading to conflicts with plugin developers who may utilize it for their own purposes. (It's unlikely anyone will name a plugin appName
, so there's no risk in this specific case).
A recommended alternative to globalizing properties is exporting a useStuff()
function.
In your scenario:
export function useAppName () { return 'Vue 3' }
// or even:
export const useAppName = () => 'Vue 3'
In any component:
import { useAppName } from '@/path/to/function'
setup () {
const appName = useAppName()
return {
appName // accessible in templates and hooks
}
}
The benefits:
- adheres to Composition API naming conventions
- automatically infers all types when sharing more complex data than just primitives (e.g., modules, functions, services, etc...) This is particularly advantageous in
setup()
functions.
- limits exposure and scope of your
stuff
only where needed, rather than globally across all components of your app. Additionally, if only required in the setup()
function, there's no need to expose it to templates or hooks.
Example of using a random (but real) plugin:
Create a plugin file (e.g., /plugins/gsap.ts
):
import gsap from 'gsap'
import ScrollToPlugin from 'gsap/ScrollToPlugin'
// configure the plugin globally
gsap.registerPlugin(ScrollToPlugin)
export function useGsap () {
return gsap
}
In any component:
import { defineComponent } from 'vue'
import { useGsap } from '@/plugins/gsap'
export defineComponent({
setup () {
const gsap = useGsap()
// correctly typed gsap variable here (if plugin has typings)
// no need for type casting
return {
gsap // optionally provide to hooks and template
} // if required outside setup()
}
})