How to register a global directive in Vue for entire app
How can i register a Vue directive so it's available in all of my components of my Vue application? I'm using Vue 2
The docs say you can register global but where in my project do I add this Vue.directive(....)
src/directives/TestMe.js
import Vue from 'vue'
export default Vue.directive('test-me', {
inserted(el) {
el.style.backgroundColor = 'red'
},
})
src/components/SignInForm.vue
<template>
<div>
<code v-test-me>
Hello World
</code>
</div>
</template>
</script>
I know the current way of doing this by doing the following. However it's not practical if I plan on using my directive in multiple components and pages of my application.
<template>
<div>
<code v-test-me>
Hello World
</code>
</div>
</template>
<script>
import TestMe from '../../directives/TestMe'
export default {
directives: {
TestMe
}
}
</script>
Updated Updated post based on answers below.
I've created a different files for each directive and then have an index.js file where i import all my directives. How can i initiate that index.js file in the directives folder at the start of my application?
// src/directives/TestMe.js
export default testMe = {
inserted(el) {
el.style.backgroundColor = 'red'
},
}
// src/directives/index.js
import testMe from './TestMe'
export default {
install(Vue) {
Vue.directive('test-me', testMe)
// Vue.directive('other-directive', myOtherDirective)
},
}
// src/main.js
import Vue from 'vue'
import App from './App.vue'
import ???? from './directives'
const app = createApp(App)
app.use(????)
You have globalDirectives...where does that name come from?
EDIT: I didn't read that OP is using Vue 2.
To call .use()
, you need to export object with function
install(Vue)
If you want the directive as a separate file.
// src/directives/TestMe.js
const testMe = {
inserted(el) {
el.style.backgroundColor = 'red'
},
}
export default testMe
Here is where you register all the directives. You can import files or just define your directives here.
// src/directives/index.js
import testMe from './TestMe'
// const myOtherDirective = {
// ...
// }
export default {
install (Vue) {
Vue.directive('test-me', testMe)
// Vue.directive('other-directive', myOtherDirective)
}
}
Here is how to register directives in Vue 2
You can register the global directives in main.js with Vue.use
// src/main.js
import Vue from 'vue'
import App from './App.vue'
import globalDirectives from './directives'
Vue.use(globalDirectives)
const app = new Vue({
router,
store,
render: h => h(App),
})
app.$mount('#app')
Here is how to register directives in Vue 3
You can register the global directives in main.js after createApp
// src/main.js
import Vue from 'vue'
import App from './App.vue'
import globalDirectives from './directives'
const app = createApp(App)
app.use(globalDirectives)