可以在条件上设置指令吗?
我有一个“粘性”指令,让元素在屏幕上粘性。我有一个社交分享组件,我正在使用它
<tempalte>
<div class="social-share" v-sticky>
....
</div>
</template>但是,现在我需要一个条件。我喜欢在道具上做这个。
<social-share :is-sticky="true">有没有简单的方法来添加指令?
我尝试使用v-bind /来绑定它:
<div class="social-share" :v-sticky="isSticky">但这将以在标签中呈现"v-sticky“而告终。
发布于 2016-05-30 21:36:54
请记住,最初的问题是在2016年提出的!因此,这是一个vue 1.x解决方案
好的,让它在指令参数上工作。并在指令本身中添加了条件。
更新
由于需要,下面是一些示例代码: SocialShare.vue是具有粘滞指令的父组件。
如您所见,带有粘滞指令的div接收一个在指令中定义的正确的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>好了,现在是指令。您可以将参数添加到指令本身。这就是sticky在div元素上工作的原因。
您只需在参数数组中声明您的props,然后就可以通过this.params访问它
// sticky directive
const sticky = {
params: [
'sticky'
],
bind() {
if (this.params.sticky) {
console.log('Set to true')
}
}
unbind() {
},
}
export default sticky发布于 2018-08-31 09:33:59
当没有向指令传递任何值时,您可以考虑缺省为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>发布于 2018-07-13 03:22:27
我偶然发现了这一点,但是解决方案是针对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 stickyhttps://stackoverflow.com/questions/37526888
复制相似问题