As the title of the question says. How can I set my helper class globally. So that I don't have to import it in every component. What are the possibilities?
Asked
Active
Viewed 278 times
0
-
You can just bind it to `window` – qqilihq Sep 06 '22 at 14:03
-
@qqilihq Thank u! To be honest, I would try not to use the window scope for that. – Max Pattern Sep 06 '22 at 14:06
-
You shouldn't do that for the same reason `window` is not desirable, https://stackoverflow.com/questions/10525582/why-are-global-variables-considered-bad-practice . IDEs provide autoimport feature, so you don't have to write imports each time you use it. Another thing is the use in templates, this would require extra boilerplate, and it's possible to expose a variable for all comps, as the answer shows for Vue 2 – Estus Flask Sep 06 '22 at 20:46
1 Answers
0
Hi as Andrew v said you can directly use the prototype key and add it to your Vue app for Vue2:
import Vue from 'vue'
import { HelperClass } from '@/assets/js/myFunc.js';
Vue.prototype.$HelperClass = HelperClass
And then
this.$HelperClass.myFunc()
How to import my own class or method globally in Vue?
Otherwise for vue 3:
export default class {
myFunc() {
alert("Exported Class")
}
}
You can provide it for all your app using provide/inject:
import { createApp } from 'vue'
import App from './App.vue'
import HelperClass from './class'
const helperClass = new HelperClass();
createApp(App)
.provide('helperClass', helperClass)
.mount('#app')
import { inject } from 'vue'
export default {
setup() {
const message = inject('helperClass')
console.log(message.myFunc())
return { message }
}
}
Or in each .vue
file needed with Composition Api:
import { ref } from 'vue'
import HelperClass from './whateveryourpathis'
export default {
setup() {
const helperClass = ref(new HelperClass())
console.log(helperClass.value.myFunc())
}
}
Or if you use the setup tag on the script
<script setup>
import { ref } from 'vue'
import HelperClass from './whateveryourpathis'
const helperClass = ref(new HelperClass())
console.log(helperClass.value.myFunc())
</script>

Sayf-Eddine
- 559
- 6
- 15
-
I using vue 3. I have this line: `import { createApp } from "vue"; const app = createApp(App); ... ` in my main.js. What i have to change to append the helper class to the app? – Max Pattern Sep 06 '22 at 21:02
-