条件添加vue指令

时间:2016-05-30 13:26:33

标签: vue.js

是否可以在条件上设置指令?

我有一个"粘"指令使元素在屏幕上粘滞。 我有一个社交分享组件,我正在使用它

<tempalte>
    <div class="social-share" v-sticky>
        ....
    </div>
</template>

然而,现在我需要一个条件。我很乐意在支柱上做这件事。

<social-share :is-sticky="true">

是否有一种简单的方法来添加指令?

我试图用v-bind /:

绑定它
<div class="social-share" :v-sticky="isSticky">

但是最终会有渲染&#34; v-sticky&#34;进入标签。

3 个答案:

答案 0 :(得分:4)

确定它可以使用指令参数。 并在指令本身中添加了条件。

<强> 更新

因为请求,这里有一些示例代码: SocialShare.vue是具有粘性指令的父组件。

如您所见,带有sticky指令的div接收在指令内定义的prop sticky

// 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>

现在好了指令。 您可以将params添加到指令本身。这就是为什么sticky适用于div元素。

您只需在params数组中声明道具,然后可以通过this.params

访问它
// sticky directive

const sticky =  {
   params: [
    'sticky'
  ],
  bind() { 
    if (this.params.sticky) {
      console.log('Set to true')
    }
  }

  unbind() {

  },
}

export default sticky

答案 1 :(得分:2)

当没有值传递给指令时,您可以考虑默认为true。

bind(el, binding) {
    if ((! binding.hasOwnProperty('value')) || binding.value) {
        // The user wants the directive to be applied...
    }
}

在您的模板中:

<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>

答案 2 :(得分:0)

我偶然发现了这个问题,但是解决方案是针对V1的,此后,他们从v指令中删除了参数。绑定在替代方法中有很多值

https://vuejs.org/v2/guide/custom-directive.html#Directive-Hook-Arguments

替代解决方案

// 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>

   // sticky directive

const sticky =  {
  bind(binding) { 
    if (binding.value) {
      console.log('Set to true')
    }
  }

  unbind() {

  },
}

export default sticky