provide/inject不能在插槽里使用?

淡若清风过
  • 76
贵州

[Vue warn]: injection "a" not found.

app.vue

<Menu>
        <MenuItem>
          <i class="fa fa-home"></i>
          <small>Navigation</small>
        </MenuItem>
</Menu>

menu.vue

<script setup lang="ts">
import { provide } from 'vue'
import type { InjectionKey } from 'vue'

const key = Symbol() as InjectionKey<Function>

const a = (name: string) => {
  return name
}

provide(key, a)
</script>

<template>
  <ul class="menu">
    <slot></slot>
  </ul>
</template>

menu-item.vue

<script setup lang="ts">
import { inject, ref } from 'vue'

const a = inject('a')
console.log(a); // injection "a" not found. 

const isActive = ref(false)
</script>

<template>
  <li :class="{active: isActive}">
    <a href="javascript:void(0);">
      <slot></slot>
    </a>
  </li>
</template>
回复
阅读 967
3 个回答
provide('a', a)

你要定义 symbol 的话,需要再单独维护一份 key.ts 对 key export,然后在 inject 时引入这个 key,这样子相对会严谨一些,写一些库的话就推荐用 symbol 。普通应用的话直接字符串咯,但主要还是看自己取舍

宣传栏