Add vue directive on condition
You may consider defaulting to true when no value is passed to the directive.
bind(el, binding) {
if ((! binding.hasOwnProperty('value')) || binding.value) {
// The user wants the directive to be applied...
}
}
In your template:
<template>
<social-share v-sticky> <!-- Will apply the directive -->
<social-share v-sticky="true"> <!-- Will apply the directive -->
<social-share v-sticky="false"> <!-- Will NOT apply the directive -->
</template>
I stumbled upon this, however the solution was for V1 and since then they have removed the params from the v-directive. The binding has many values in alternative tho
https://v2.vuejs.org/v2/guide/custom-directive.html#Directive-Hook-Arguments
An alternative solution
// SocialShare.vue
<template>
<div class="social-share" v-sticky="true">
<h5>{{ headline }}</h5>
// your code here.
</div>
</template>
<script>
import stickyDirective from '../../directives/sticky';
export default {
directives: {
'sticky': stickyDirective,
}
}
</script>
and
// sticky directive
const sticky = {
bind(binding) {
if (binding.value) {
console.log('Set to true')
}
}
unbind() {
},
}
export default sticky
Please keep in mind, that the original question was asked 2016! Thus this is a vue 1.x solution
ok got it working over directive params. And added the condition in the directive itself.
Update
Because requested, here is some example code: The SocialShare.vue is the parent component which has the sticky directive.
As you see, the div with the sticky directive receive a prop sticky
which is defined inside the directive.
// SocialShare.vue
<template>
<div class="social-share" v-sticky :sticky="true">
<h5>{{ headline }}</h5>
// your code here.
</div>
</template>
<script>
import stickyDirective from '../../directives/sticky';
export default {
directives: {
'sticky': stickyDirective,
}
}
</script>
Ok now the directive.
You can add params to directives itself. Thats why sticky
works on a div element.
You simply declare your props in a params array and can then access it over this.params
// sticky directive
const sticky = {
params: [
'sticky'
],
bind() {
if (this.params.sticky) {
console.log('Set to true')
}
}
unbind() {
},
}
export default sticky