vue.js - 在条件下添加 vue 指令

标签 vue.js

是否可以根据条件设置指令?

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

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

但是,现在我需要一个条件。我很乐意通过 Prop 制作它。

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

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

我尝试用 v-bind/绑定(bind)它:

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

但这最终会在标签中呈现“v-sticky”。​​

最佳答案

当没有值传递给指令时,您可以考虑默认为 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>

关于vue.js - 在条件下添加 vue 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37526888/

相关文章:

javascript - Vue JS通过唯一id删除数组中的对象?

javascript - Vue js v-autocomplete 不能正确更新动态更改的项目

javascript - Webpack 开发服务器不热重新加载 .vue 文件

vue.js - 如果我刷新我的网页,Vuex 存储为空

vue.js - 使用 Vue.js 添加自动广告

javascript - vuejs 获取所选类的值

javascript - Vue.js 无法解析过滤器 : key

javascript - VueJS 中的秒到分钟

javascript - Buefy 工具提示中的新行

unit-testing - 如何修复 Jest 错误 : TypeError: $ is not a function