codejump

Options API Deep-dive

Preview — 3 of 10 questions

What is the difference between watch and watchEffect?

javascript
<script setup>
import { ref, watch, watchEffect } from 'vue'

const query = ref('')
const results = ref([])

// Option A
watch(query, (newVal) => {
  fetchResults(newVal)
})

// Option B
watchEffect(() => {
  fetchResults(query.value)
})
</script>
Awatch is synchronous and watchEffect is asynchronous.
BwatchEffect can observe only one variable, while watch can observe several.
Cwatch explicitly observes a source and exposes old and new values; it does not run immediately by default. watchEffect tracks its dependencies automatically and runs immediately.
DThey are identical; watchEffect is an alias for watch.

What is a Vue 3 composable, and why might you use one instead of a mixin?

javascript
// useCounter.js
import { ref } from 'vue'

export function useCounter(initial = 0) {
  const count = ref(initial)
  function increment() { count.value++ }
  function reset() { count.value = initial }
  return { count, increment, reset }
}

<script setup>
import { useCounter } from './useCounter'

const { count, increment, reset } = useCounter(10)
</script>
AA composable is a function that packages reusable stateful logic with the Composition API. Unlike mixins, its value origins are explicit, name collisions are easier to avoid, and TypeScript types are straightforward.
BA composable is a CSS file unrelated to Vue logic.
CComposables replace components, so .vue files are no longer needed.
DComposables cannot use lifecycle hooks.

When would you use provide/inject instead of passing props through every level?

javascript
<!-- GrandParent.vue -->
<script setup>
import { provide, ref } from 'vue'

const theme = ref('dark')
provide('theme', theme)
</script>

<!-- DeepChild.vue (plusieurs niveaux plus bas) -->
<script setup>
import { inject } from 'vue'

const theme = inject('theme', 'light') // 'light' = default
</script>
AThey always replace props; props should never be used again.
Bprovide can pass only primitive strings and numbers.
Cinject creates a non-reactive local copy, so parent changes cannot reach the child.
DThey share values across a component subtree without prop drilling, for example a theme, configuration, or shared service.

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.