Vue.js Directives — Arguments and Values

John Au-Yeung
The Startup
Published in
3 min readApr 9, 2020

--

Photo by Lee Dobson 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 how to make our directives accept arguments and values to directives and use them in our code.

Dynamic Directive Arguments

We can pass in arguments and values to a directive and then get these values from the binding parameter.

For example, we can make a directive that takes an argument and value as follows:

src/index.js :

Vue.directive("position", {
bind(el, binding, vnode) {
const validPositions = ["relative", "fixed", "absolute"];
if (validPositions.includes(binding.arg)) {
el.style.position = binding.arg;
el.style.top = `${binding.value}px`;
}
}
});
new Vue({
el: "#app",
data: {
message: "Hello"
}
});

index.html :

<!DOCTYPE html>
<html>
<head>
<title>App</title>
<meta charset="UTF-8" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<p v-position:absolute="50">{{message}}</p>
</div>
<script src="src/index.js"></script>
</body>
</html>

--

--