Reputation: 7827
is it possible to set a directive on a condition?
I have a "sticky" directive to make elements sticky on the screen. And I have a social share component where I am using it
<tempalte>
<div class="social-share" v-sticky>
....
</div>
</template>
However, now I need a condition. I would love making this over a prop.
<social-share :is-sticky="true">
Is there an easy way to add the directive?
I've tried to bind it with v-bind / :
<div class="social-share" :v-sticky="isSticky">
But this will end up, with rendering "v-sticky" into the tag.
Upvotes: 22
Views: 21730
Reputation: 107
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
Upvotes: 1
Reputation: 1036
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>
Upvotes: 17
Reputation: 7827
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
Upvotes: 4