[Vuejs]-How to pass data down to a component via custom directive in Vue3?

0👍

Disclaimer

This is hacky, and probably not the way to go because it going against the Vue API (which is clearly saying that it’s read only), so yeah: you probably don’t want to use it that way.

Also, a directive is used for DOM element modifications, not to reach and mutate a Vue state elsewhere. My team’s needs are very hacky.
Don’t reproduce it at home, use regular props instead.


Meanwhile, if you do, here is how.

page.vue

<template>
  <simple-div v-layer="'pizza'">
</template>

<script>
export default {
  directives: {
    layer: {
      mounted(_el, binding, vnode) {
        vnode.ref.i.data.layer = binding.value
      },
    },
  },
}
</script>

SimpleDiv.vue

<template>
  <div ref="layerHack">  <!-- this ref is required -->
    <div>{{ layer }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      layer: null,
    }
  },
}
</script>

Leave a comment