I have a Vue SFC Playground
My display and display-two component need access to a data provided by provider. The computation of this data is expensive and provider should only exist if needed.
display-three has no need for the data provided by provider.
For various reasons, in the real case, it is impractical to place provider and display-three inside of displayer.
When either display, display-two, or display-three are to be displayed, I would like to send the created component to the named slot todisplay
inside of displayer. I am not sure how to do that or if it is possible.
Here is the code for reference:
App.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>
Display.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>
Displayer.vue
<template>
<div style="background-color: red;">
<slot name="todisplay"/>
</div>
</template>
<script setup>
</script>
I have an alternative if this turns out to not be possible. I am curious to find out if it is. If it is, how?