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?
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?
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>