codejump

Advanced Patterns

Preview — 3 of 10 questions

How does Vue 3 track reactive dependencies under the hood?

javascript
// Vue 3 pseudo-code (simplified)
let activeEffect = null

function track(target, key) {
  if (activeEffect) {
    // store: target → key → Set of effects
    getOrCreateDep(target, key).add(activeEffect)
  }
}

function trigger(target, key) {
  getOrCreateDep(target, key).forEach(effect => effect())
}
AVue uses JavaScript Proxies to intercept property reads and writes. While an effect runs, Vue records which properties it reads; changes to those properties can trigger the effect again.
BVue uses the deprecated Object.observe() API to detect changes.
CVue polls all reactive data every 16 milliseconds with requestAnimationFrame.
DVue 3 uses Object.defineProperty getters and setters in the same way as Vue 2.

What happens when the nested state changes in this example?

javascript
import { ref, shallowRef } from 'vue'

// Deep reactive (default)
const deepState = ref({ user: { profile: { name: 'Alice' } } })

// Shallow reactive
const shallowState = shallowRef({ user: { profile: { name: 'Alice' } } })

// Which triggers a re-render?
deepState.value.user.profile.name = 'Bob'   // ?
shallowState.value.user.profile.name = 'Bob' // ?
AMutating deepState triggers a render because ref makes the nested object reactive. Mutating the object inside shallowState does not trigger one; shallowRef tracks replacement of .value, not nested mutations.
BBoth mutations trigger a render; ref and shallowRef are identical for objects.
CNeither mutation triggers a render; both require a manual triggerRef() call.
DshallowRef becomes deeply reactive after two levels of nesting.

Why does this parent component fail to call the child's method as expected?

javascript
<!-- Child.vue -->
<script setup>
const secretMethod = () => console.log('secret')
const publicMethod = () => console.log('public')
</script>

<!-- Parent.vue -->
<script setup>
import { ref } from 'vue'
const childRef = ref()
// After mount:
childRef.value.secretMethod() // ❌ Error?
childRef.value.publicMethod() // ❌ Error?
</script>
ATemplate refs do not work with <script setup>; the child must use the Options API.
BThe child must use ref() to make its methods visible to the parent.
CA <script setup> component is closed to parent refs by default. The child must explicitly expose public members with defineExpose().
DThe parent must call childRef.value.$el.publicMethod().

Sign up free to play

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