如何在模板外部创建的命名槽中使用 vue 组件?

问题描述 投票:0回答:1

我有一个Vue SFC Playground

我的显示和显示两个组件需要访问提供者提供的数据。这些数据的计算成本很高,提供者应该仅在需要时才存在。

display-3 不需要提供商提供的数据。

由于种种原因,在实际情况下,将provider和display-3放在displayer内部是不切实际的。

当要显示显示、显示二或显示三时,我想将创建的组件发送到显示器内部的命名插槽

todisplay
。我不确定如何做到这一点或是否可能。

以下是参考代码:

应用程序.vue

<template>
  <button @click="rotate">Rotate</button>
  
  <displayer>
    <template #todisplay>
      <!-- either display, display-two, or display-three displayed ONLY here -->
    </template>
  </displayer>  

  <provider v-if="providerDisplay">
    <display v-if="which === 0" />
    <display-two v-if="which === 1" />
  </provider>

  <display-three v-if="which === 2" />
  
</template>


<script setup>
import { ref, computed } from 'vue'

const which = ref(0)

import Provider from './Provider.vue'
import Display from './Display.vue'
import DisplayTwo from './DisplayTwo.vue'
import DisplayThree from './DisplayThree.vue'
import Displayer from './Displayer.vue'

const providerDisplay = computed(() => which.value === 0 || which.value === 1)

function rotate() {
  which.value = ( which.value + 1 ) % 3
}

</script>

Provider.vue

<template>
  <slot />
</template>


<script setup>
import { provide, ref } from 'vue'

const variable = ref("hello, world!")

provide( 'variable', variable )
</script>

显示.vue

<template>
  <div>
    Display {{ variable }}
  </div>
</template>


<script setup>
import { inject } from 'vue'

const variable = inject('variable')

</script>

DisplayTwo.vue

<template>
  <div>
    Display Two {{ variable }}
  </div>
</template>


<script setup>
import { inject } from 'vue'

const variable = inject('variable')

</script>

DisplayThree.vue

<template>
  <div>
    Display Three
  </div>
</template>


<script setup></script>

显示器.vue

<template>
  <div style="background-color: red;">
    <slot name="todisplay"/>
  </div>
</template>


<script setup>
</script>

如果事实证明这是不可能的,我还有一个替代方案。我很好奇是否是这样。如果是的话,怎么办?

vue.js vuejs-slots
1个回答
0
投票

动态组件

  <displayer>
    <template #todisplay>
      <!-- either display, display-two, or display-three displayed ONLY here -->
      <component :is="current"></component>
    </template>
  </displayer>  

...


let current = ref(Display);

const comps = {
  0: Display,
  1: DisplayTwo,
  2: DisplayThree
}

function rotate() {
  which.value = ( which.value + 1 ) % 3
  current.value = comps[which.value]
}
© www.soinside.com 2019 - 2024. All rights reserved.