阿里云主机折上折
  • 微信号
Current Site:Index > Handling edge cases in responsive systems

Handling edge cases in responsive systems

Author:Chuan Chen 阅读数:24078人阅读 分类: Vue.js

Handling Edge Cases in the Reactive System

Vue 3's reactivity system is based on Proxy, which provides stronger capabilities compared to Vue 2's Object.defineProperty. However, certain edge cases still require special handling. These include reactivity for primitive values, array operations, property deletion, NaN handling, and more.

Reactivity for Primitive Values

Proxy cannot directly proxy primitive values (string, number, boolean, etc.). Vue 3 wraps them using the ref() function:

const count = ref(0) // Actually creates a reactive object like { value: 0 }  

// Automatic unwrapping in templates  
// <div>{{ count }}</div> No need to write count.value  

Special attention is needed when updating primitive values reactively:

let state = reactive({  
  primitive: 'initial' // Primitive property  
})  

// Direct replacement loses reactivity  
state.primitive = 'new value' // Works  
state = { primitive: 'another' } // Fails, because the entire state object is reassigned  

Special Handling for Arrays

While Proxy can detect array index changes, certain operations still require special handling:

const arr = reactive([1, 2, 3])  

// These methods trigger reactivity  
arr.push(4)  
arr.splice(0, 1)  

// Directly setting length does not trigger reactivity  
arr.length = 0 // Won't trigger updates  
// Instead, use:  
arr.splice(0) // Will trigger updates  

Handling sparse arrays:

const sparse = reactive([])  
sparse[100] = 'value' // Triggers reactivity, but Vue creates 100 empty items  

// Recommended approach:  
sparse.splice(100, 1, 'value')  

Reactivity for Property Deletion

When using the delete operator:

const obj = reactive({ prop: 'value' })  

delete obj.prop // Triggers reactivity  

But for collection types like Map/Set:

const map = reactive(new Map())  
map.delete('key') // Won't trigger reactivity  
// Correct approach:  
const map = reactive(new Map())  
set(() => map.delete('key')) // Needs to be wrapped in an effect  

NaN Equality Comparison

In JavaScript, NaN !== NaN, which can cause issues in the reactivity system:

const state = reactive({ value: NaN })  

watch(() => state.value, (newVal) => {  
  console.log('changed:', newVal)  
})  

state.value = NaN // Still triggers because Vue handles it internally  

Handling Circular References

When an object has circular references:

const obj = reactive({})  
obj.self = obj // Creates a circular reference  

// Vue handles this correctly  
console.log(obj.self.self === obj) // true  

But caution is needed when converting to a plain object:

const plain = JSON.parse(JSON.stringify(obj)) // Throws a circular reference error  

Handling Non-Configurable Properties

When an object property is marked as non-configurable (configurable: false):

const obj = {}  
Object.defineProperty(obj, 'prop', {  
  value: 'static',  
  configurable: false  
})  

const reactiveObj = reactive(obj)  
// Attempting to modify silently fails  
reactiveObj.prop = 'new value' // No effect  

Reactivity for Prototype Chain Properties

Properties on the prototype chain are not proxied by default:

const parent = { parentProp: 'value' }  
const child = reactive(Object.create(parent))  

console.log(child.parentProp) // 'value'  
child.parentProp = 'new' // Won't trigger reactivity, because it operates on the prototype  

Edge Cases in Async Update Queue

Multiple modifications in the same event loop:

const state = reactive({ count: 0 })  

state.count++  
state.count++  
// Only triggers one update  

To force synchronous updates:

import { flushSync } from 'vue'  

flushSync(() => {  
  state.count++  
  state.count++  
}) // Triggers two updates  

Marking Reactive Objects

Vue internally uses __v_skip to skip reactivity conversion:

const obj = { __v_skip: true }  
const reactiveObj = reactive(obj) // Skips proxying and returns the original object  

Performance Optimization for Large Arrays

Handling large arrays reactively can cause performance issues:

const largeArray = reactive(new Array(1000000).fill(0))  

// More efficient read-only handling  
const readonlyArray = readonly(largeArray) // Doesn't create proxies for each element  

Custom Reactive Behavior

Implementing custom reactivity logic with customRef:

function customRef(factory) {  
  let value  
  return {  
    get() {  
      track(this, 'value')  
      return value  
    },  
    set(newVal) {  
      value = factory(newVal)  
      trigger(this, 'value')  
    }  
  }  
}  

const age = customRef((val) => {  
  return Math.max(0, Math.min(120, val)) // Limits age to 0-120  
})  

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.