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?

binaryfunt
  • 6,401
  • 5
  • 37
  • 59
Katerou22
  • 777
  • 5
  • 19
  • I think you will need to have the directive keep a registry of elements. – Roy J Oct 09 '18 at 22:20
  • 3
    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)) } })` – Sphinx Oct 09 '18 at 23:11
  • I know this sounds stupid and does't make alot of sense.. But what happens if you put an unique [key](https://vuejs.org/v2/guide/list.html#key) on each of the buttons? - Maybe Vue is trying to re-use your button wrongly ¯\_(ツ)_/¯ – Sølve T. Oct 10 '18 at 07:21
  • @Sphinx , 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) }) })` – Katerou22 Oct 10 '18 at 15:34

1 Answers1

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)
  }
})
tony19
  • 125,647
  • 18
  • 229
  • 307
Lucas
  • 1,833
  • 1
  • 18
  • 19