首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在条件上添加vue指令

在条件上添加vue指令
EN

Stack Overflow用户
提问于 2016-05-30 21:26:33
回答 3查看 13.3K关注 0票数 17

可以在条件上设置指令吗?

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

代码语言:javascript
复制
<tempalte>
    <div class="social-share" v-sticky>
        ....
    </div>
</template>

但是,现在我需要一个条件。我喜欢在道具上做这个。

代码语言:javascript
复制
<social-share :is-sticky="true">

有没有简单的方法来添加指令?

我尝试使用v-bind /来绑定它:

代码语言:javascript
复制
<div class="social-share" :v-sticky="isSticky">

但这将以在标签中呈现"v-sticky“而告终。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-05-30 21:36:54

请记住,最初的问题是在2016年提出的!因此,这是一个vue 1.x解决方案

好的,让它在指令参数上工作。并在指令本身中添加了条件。

更新

由于需要,下面是一些示例代码: SocialShare.vue是具有粘滞指令的父组件。

如您所见,带有粘滞指令的div接收一个在指令中定义的正确的sticky

代码语言:javascript
复制
// 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>

好了,现在是指令。您可以将参数添加到指令本身。这就是sticky在div元素上工作的原因。

您只需在参数数组中声明您的props,然后就可以通过this.params访问它

代码语言:javascript
复制
// sticky directive

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

  unbind() {

  },
}

export default sticky
票数 4
EN

Stack Overflow用户

发布于 2018-08-31 09:33:59

当没有向指令传递任何值时,您可以考虑缺省为true。

代码语言:javascript
复制
bind(el, binding) {
    if ((! binding.hasOwnProperty('value')) || binding.value) {
        // The user wants the directive to be applied...
    }
}

在您的模板中:

代码语言:javascript
复制
<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>
票数 15
EN

Stack Overflow用户

发布于 2018-07-13 03:22:27

我偶然发现了这一点,但是解决方案是针对V1的,从那时起,他们就从v指令中删除了参数。绑定在另一种情况下有很多值

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

另一种解决方案

代码语言:javascript
复制
// 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>

代码语言:javascript
复制
   // sticky directive

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

  unbind() {

  },
}

export default sticky
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37526888

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档