codejump

Vue Expert

Preview — 3 of 10 questions

Vue compiles templates into optimized render functions. What does this patch flag value mean?

javascript
// Compiled output of:
// <div :class="cls">{{ msg }}</div>

import { createElementVNode as _createElementVNode, toDisplayString as _toDisplayString, normalizeClass as _normalizeClass, openBlock as _openBlock, createElementBlock as _createElementBlock } from "vue"

export function render(_ctx) {
  return (_openBlock(), _createElementBlock("div", {
    class: _normalizeClass(_ctx.cls)
  }, _toDisplayString(_ctx.msg), 3 /* TEXT, CLASS */))
}
A3 is the node's index in the virtual DOM.
B3 means the element has three children.
C3 combines the TEXT (1) and CLASS (2) bit flags. The compiler marks these dynamic parts so Vue can check them selectively during updates.
DPatch flags are used only for SSR; client rendering always performs a full diff.

What does effectScope do, and when is it useful?

javascript
import { effectScope, ref, watchEffect, computed } from 'vue'

function createFeature() {
  const scope = effectScope()

  scope.run(() => {
    const count = ref(0)
    const double = computed(() => count.value * 2)
    watchEffect(() => console.log(count.value))
    // All effects registered here belong to this scope
  })

  return {
    stop: () => scope.stop() // stops all effects at once
  }
}
AIt creates a separate worker thread for reactive effects.
BIt groups effects such as computed values and watchers so they can be stopped together, which is useful in stores, plugins, and dynamically activated composables.
CIt is an alias for onScopeDispose.
DEffects created in an effectScope can never be garbage collected.

How can a composable accept plain values, refs, and getter functions?

javascript
import { toValue, watchEffect, ref } from 'vue'

function useFetch(url) {
  const data = ref(null)

  watchEffect(() => {
    // Works whether url is a string, ref, or getter function
    const resolvedUrl = toValue(url)
    fetch(resolvedUrl).then(r => r.json()).then(d => data.value = d)
  })

  return { data }
}

// All these usages work:
useFetch('/api/static')           // plain string
useFetch(ref('/api/dynamic'))     // ref
useFetch(() => `/api/${userId}`)  // getter (reactive)
AtoValue() resolves a ref to .value, invokes a getter function, or returns a plain value unchanged.
BtoValue() converts every value to a string.
CtoValue() behaves exactly like unref() for getter functions.
DVue 3 has no toValue() function; the correct name is resolveValue().

Sign up free to play

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