0
0
Vueframework~10 mins

Compound components pattern in Vue - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a parent component that provides context to its children.

Vue
<script setup>
import { ref, provide } from 'vue'
const state = ref(false)
provide('[1]', state)
</script>
Drag options to blanks, or click blank then click option'
AcontextValue
BuseState
CtoggleState
DsharedValue
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic key like 'useState' which is not descriptive.
Forgetting to use provide to share state.
2fill in blank
medium

Complete the code to inject the provided state in a child component.

Vue
<script setup>
import { inject } from 'vue'
const toggleState = inject('[1]')
</script>
Drag options to blanks, or click blank then click option'
AtoggleState
BcontextValue
CsharedValue
DuseState
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different key than the parent component's provide key.
Not using inject to access the shared state.
3fill in blank
hard

Fix the error in the child component to toggle the shared state correctly.

Vue
<script setup>
import { inject } from 'vue'
const toggleState = inject('toggleState')
function toggle() {
  toggleState[1] = !toggleState.value
}
</script>
Drag options to blanks, or click blank then click option'
Avalue
B.value
Cref
Dstate
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning directly to toggleState instead of toggleState.value.
Using incorrect property names like 'ref' or 'state'.
4fill in blank
hard

Fill both blanks to create a compound component with a parent and a child that toggles visibility.

Vue
<template>
  <div>
    <button @click="[1]">Toggle</button>
    <slot v-if="[2]"></slot>
  </div>
</template>

<script setup>
import { ref } from 'vue'
const visible = ref(false)
function toggle() {
  visible.value = !visible.value
}
</script>
Drag options to blanks, or click blank then click option'
Atoggle
Bvisible.value
Cvisible
Dtoggle()
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'visible' instead of 'visible.value' in the template.
Calling toggle as 'toggle()' in the template event binding.
5fill in blank
hard

Fill all three blanks to complete a compound component pattern with provide/inject and toggle logic.

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

const visible = ref(false)
function toggle() {
  visible.value = !visible.value
}

provide('[1]', visible)
provide('[2]', toggle)

const injectedVisible = inject('[3]')
</script>
Drag options to blanks, or click blank then click option'
Avisible
Btoggle
DtoggleState
Attempts:
3 left
💡 Hint
Common Mistakes
Using different keys for provide and inject.
Providing toggleState instead of toggle.