0
0
Vueframework~10 mins

State machines with composables 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 import the Vue Composition API function used to create reactive state.

Vue
import { [1] } from 'vue';

export function useCounter() {
  const count = [1](0);
  return { count };
}
Drag options to blanks, or click blank then click option'
Acomputed
Breactive
Cref
Dwatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using reactive instead of ref for a simple number.
Trying to use computed when no derived value is needed.
2fill in blank
medium

Complete the code to define a state machine with two states: 'idle' and 'loading'.

Vue
import { ref } from 'vue';

export function useLoader() {
  const state = ref('idle');

  function startLoading() {
    state.value = [1];
  }

  return { state, startLoading };
}
Drag options to blanks, or click blank then click option'
A'idle'
B'loading'
C'done'
D'error'
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning the wrong state string like 'idle' again.
Forgetting to use quotes around the state string.
3fill in blank
hard

Fix the error in the composable by completing the code to toggle between 'on' and 'off' states.

Vue
import { ref } from 'vue';

export function useToggle() {
  const state = ref('off');

  function toggle() {
    state.value = state.value === 'off' ? [1] : 'off';
  }

  return { state, toggle };
}
Drag options to blanks, or click blank then click option'
A'off'
B'idle'
C'loading'
D'on'
Attempts:
3 left
💡 Hint
Common Mistakes
Setting the state to 'off' again, causing no change.
Using unrelated state strings like 'loading'.
4fill in blank
hard

Fill both blanks to create a computed property that returns true if the state is 'active'.

Vue
import { ref, computed } from 'vue';

export function useActiveState() {
  const state = ref('inactive');

  const isActive = computed(() => state.value [1] [2]);

  return { state, isActive };
}
Drag options to blanks, or click blank then click option'
A===
B!==
C'active'
D'inactive'
Attempts:
3 left
💡 Hint
Common Mistakes
Using !== instead of === causing the logic to invert.
Comparing to 'inactive' instead of 'active'.
5fill in blank
hard

Fill the blanks to create a composable that manages a state machine with 'start', 'pause', and 'stop' states and a function to set the state.

Vue
import { ref } from 'vue';

export function usePlayer() {
  const state = ref([1]);

  function setState(newState) {
    if (['start', 'pause', 'stop'].includes(newState)) {
      state.value = [2];
    }
  }

  return { state, setState };
}
Drag options to blanks, or click blank then click option'
A'stop'
BnewState
C'start'
D'pause'
Attempts:
3 left
💡 Hint
Common Mistakes
Setting initial state to 'stop' or 'pause' instead of 'start'.
Assigning a string literal instead of the variable newState.