如何通过 Vue3 中的自定义指令将数据向下传递给组件?

How to pass data down to a component via custom directive in Vue3?

我想实现这种行为

<simple-component v-layer="'pizza'" />

使用自定义指令,将 'pizza' 传递给组件并能够在我的 SimpleComponent.
中使用它 这个想法是之后将它带到上层父范围(通过 v-slot),它很老套,可能不是最好的方法,但语法对我的客户很重要(这里输入的字符越少越好)。

我发现 this github issue 适用于 Vue2,但我不确定如何使它适用于 Vue3 甚至语法(我知道现在不是 vNode.contextbinding.instance 和另外,我们不需要 $set 因为 Vue3 使用代理)。

The documentation 并没有真正帮助我,在常规开发工具中检查实例也没有给我任何线索。

PS:我们几乎可以在 SimpleComponent 中做任何事情,我们只是不需要从组件外部看到它。

免责声明

这很 hacky,可能不是要走的路,因为它违背了 Vue API(这显然是说它是 read only),所以是的:你可能不想要以这种方式使用它。

此外,指令用于 DOM 元素修改,而不是在其他地方到达和改变 Vue 状态。我的团队的需求非常棘手。
不要在家复制,用普通道具代替。


同时,如果你这样做了,方法如下。

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>