Simple Vue Directives That’ll Save You Time

John Au-Yeung
Level Up Coding
Published in
4 min readMay 19, 2020

--

Photo by Djim Loic on Unsplash

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

In this article, we’ll look at some Vue directives that’ll save you time developing Vue apps.

V-Hotkey

The v-hotkey package let us add hot-key handling in our Vue app without too much trouble.

We can install it by running:

npm install --save v-hotkey

Then we can use it as follows:

main.js :

import Vue from "vue";
import App from "./App.vue";
import VueHotkey from "v-hotkey";
Vue.use(VueHotkey);Vue.config.productionTip = false;new Vue({
render: h => h(App)
}).$mount("#app");

App.vue :

<template>
<div id="app">
<span v-hotkey="keymap" v-show="show">Toggle me with Ctrl+Shift+H</span>
</div>
</template>
<script>
export default {
data() {
return {
show: true
};
},
methods: {
toggle() {
this.show = !this.show;
}
},
computed: {
keymap() {
return {
"ctrl+shift+h": this.toggle
};
}
}
};
</script>

In the code above, we defined the keymap computed property that has the ctrl+shift+h property. This will run a method of our choice if we press Ctrl+Shift+H to show or hide our template text above.

In our example, we run the this.toggle method to toggle this.show between true and false which is used as the condition to show our span.

The package works with the Vue built-in event modifiers luke prevent to prevent the default behavior and stop to stop the propagation of the event.

We can do that as follows:

<span v-hotkey.prevent="keymap" v-show="show">Toggle me with Ctrl+Shift+H</span>

V-Click-Outside

The v-click-outside directive lets us run some code when we click outside of some component, which is often something that we want to do.

There’s no easy way to do it without any add-ons. Therefore, this will help us. We install it by running:

--

--