根据条件添加 vue 指令 [英] Add vue directive on condition
问题描述
是否可以在条件上设置指令?
我有一个粘性"指令来使元素在屏幕上具有粘性.我有一个社交分享组件,我正在使用它
<模板><div class="social-share" v-sticky>....
</模板>
但是,现在我需要一个条件.我很想用道具来做这个.
有没有简单的方法来添加指令?
我试图用 v-bind/绑定它:
</模板><脚本>从'../../directives/sticky'导入stickyDirective;导出默认{指令:{'粘性':stickyDirective,}}
现在好了指令.您可以将参数添加到指令本身.这就是 sticky
作用于 div 元素的原因.
您只需在 params 数组中声明您的道具,然后就可以通过 this.params
//粘性指令常量粘性 = {参数: ['黏'],绑定(){如果(this.params.sticky){console.log('设置为真')}}解除绑定(){},}导出默认粘性
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.
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
这篇关于根据条件添加 vue 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!