根据条件添加 vue 指令 [英] Add vue directive on condition

查看:41
本文介绍了根据条件添加 vue 指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<模板><div class="social-share" v-sticky>....

</模板>

但是,现在我需要一个条件.我很想用道具来做这个.

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

我试图用 v-bind/绑定它:

但这最终会在标签中呈现v-sticky".​​

解决方案

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

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

更新

由于要求,这里是一些示例代码:SocialShare.vue 是具有粘性指令的父组件.

如你所见,带有 sticky 指令的 div 收到一个在指令中定义的属性 sticky.

//SocialShare.vue<模板><div class="social-share" v-sticky :sticky="true"><h5>{{ 标题 }}</h5>//你的代码在这里.

</模板><脚本>从'../../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屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆