I"m porting my new app from vue2 to vue3. Since mixins are not recommended way of reusing code in vue3, Im trying to convert them into composable.
I've 2 mixins (methods) __(key)
and __n(key, number)
in mixins/translate.js
which will translate any word into the app's locale.
module.exports = {
methods: {
/**
* Translate the given key.
*/
__(key, replace = {}) {
// logic
return translation
}
Now this is how I converted it as
Composables/translate.js
export function __(key, replace = {}) {
// logic
return translation
}
and since I need these functions to be accessbile in every component without explicitly importing. I'm importing it in app.js
import {__, __n} from '@/Composables/translate.js';
Questions
- __() is not accessible in every component. How to make this function accessible in every component without explicit import
- Is this the right of doing things?
These functions are required essentially in every component, declaring them in every component is impractical.
CodePudding user response:
#1, You can put it into the globalProperties object
import {__, __n} from '@/Composables/translate.js';
const app = createApp(AppComponent);
app.config.globalProperties.__ = __;
app.config.globalProperties.__n = __n;
#2, though opinion based, importing for every component that needs it would be my preferred way.