If all you want is to replace {{ appName }} in any any template with 'Vue 3' (string), without having to import anything, the cleanest way would be using config.globalProperties, as suggested by other answers:
const app = createApp(App).mount('#app');
app.config.globalProperties.appName = 'Vue 3'
However, you should try not to overuse this pattern. It goes against the reusability and modularization principles which drove the development of Composition API.
The main reason why you should avoid polluting globalProperties is because it serves as pollution field across Vue3 apps, so many plugin devs might decide to provide their plugin instance using it. (Obviously, nobody will ever name a plugin appName, so you run no risk in this particular case).
The recommended alternative to globalization is exporting a useStuff() function.
In your case:
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 // make it available in template and hooks
}
}
The advantages:
- it uses the Composition API naming convention
- when sharing something more complex than a primitive (could be a module, a set of functions, a service, etc...) all types are inferred, out of the box. This is particularly useful in
setup() functions.
- you only expose and scope your
stuff where you need it exposed, not in every single component of your app. Another advantage is: if you only need it in setup() function, you don't have to expose it to template or hooks.
Example usage with a random (but real) plugin:
Create a plugin file (i.e: /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()
// gsap here is typed correctly (if the plugin has typings)
// no need for casting
return {
gsap // optionally provide it to hooks and template
} // if needed outside setup()
}
})
console.log(this)to see whats going on?thisisundefinedinsidesetup()When setup is executed, the component instance has not been created yet