Multiple Elements with same custom directive vuejs
Asked Answered
D

1

8

Hey there, I have some elements with the same custom directive but different values in my page.

I want to get all elements with that directive to process on them.

When I use this code:

Vue.directive('can', function (value) {
    console.log(value)
})

it just gave me the first element with the can directive, not all of them, so how I can get all of the elements with the can directive?!

Update: my elements are like so:

<button v-can="'register-permission'">Register</button>
<button v-can="'buy-permission'">Buy</button>
<button v-can="'Sell-permission'">Sell</button>

I want to access all buttons with the v-can directive in page! How can it be done?

Dafodil answered 9/10, 2018 at 21:47 Comment(4)
I think you will need to have the directive keep a registry of elements.Abuse
as @RoyJ pointed out, do something like this: let cans = []; Vue.directive('can', { inserted: function (el, binding) { cans.push({el: el, value: binding.value}) console.log(JSON.stringify(cans)) } })Lien
I know this sounds stupid and does't make alot of sense.. But what happens if you put an unique key on each of the buttons? - Maybe Vue is trying to re-use your button wrongly ¯_(ツ)_/¯Giulia
@Lien , oh still just give me first element which uses can!, cause i want to get updated directive on listener, something like this: Bus.$on('permissionChanged', function (data) { let cans = [] Vue.directive('can', function (el, binding, vnode) { cans.push(el) console.log(cans) }) })Dafodil
C
0

Following Vuejs documentation on custom directive, I would access all of them like this:

Vue.directive('can', {
  bind: function (el, binding, vnode) {
    console.log(binding.expression)
  }
})
Chert answered 30/7, 2020 at 10:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.