1. toRaw vs markRaw
1.1 基本概念
- toRaw: 返回响应式对象的原始对象,用于临时获取原始数据结构,标记过后将会失去响应式
- markRaw: 标记一个对象永远不会转换为响应式对象,返回对象本身
1.2 使用对比
const state = reactive({
count: 0,
obj: {
nested: 'value'
}
})
const rawState = toRaw(state)
rawState.count++
const obj = markRaw({
count: 0,
nested: {
value: 'hello'
}
})
const state = reactive({
data: obj
})
state.data.count++
2. 实际应用场景
2.1 使用 toRaw 的场景
- 性能优化
const state = reactive({
list: [
]
})
const rawList = toRaw(state.list)
const result = heavyComputation(rawList)
- 与外部库集成
const state = reactive({
chartData: {
labels: ['A', 'B', 'C'],
values: [1, 2, 3]
}
})
const rawChartData = toRaw(state.chartData)
thirdPartyChart.setData(rawChartData)
2.2 使用 markRaw 的场景
- 不需要响应式的数据结构
class Helper {
format(value) {
return `formatted: ${value}`
}
}
const state = reactive({
helper: markRaw(new Helper()),
data: 'test'
})
console.log(state.helper.format(state.data))
- 大型不可变对象
const constants = markRaw({
API_ENDPOINTS: {
users: '/api/users',
posts: '/api/posts',
},
APP_CONFIG: {
}
})
const store = reactive({
config: constants,
})
3. 性能优化实践
3.1 避免不必要的响应式转换
const store = {
state: reactive({
userProfile: {
name: '',
email: ''
}
}),
utils: markRaw({
formatDate: (date) => { },
validateEmail: (email) => { }
}),
config: markRaw({
apiBase: 'https://api.example.com',
timeout: 5000
})
}
3.2 大数据处理优化
const state = reactive({
items: []
})
function processLargeData(data) {
const rawItems = toRaw(state.items)
const result = heavyComputation(rawItems)
state.items = result
}
4. 与其他 API 配合使用
4.1 与 ref 配合
const count = ref(0)
const rawCount = toRaw(count)
console.log(rawCount.value)
const obj = markRaw({ count: 0 })
const objRef = ref(obj)
4.2 与 computed 配合
const state = reactive({
firstName: 'John',
lastName: 'Doe'
})
const fullName = computed(() => {
const raw = toRaw(state)
return `${raw.firstName} ${raw.lastName}`
})
5. 注意事项
- 保持响应性
const state = reactive({
count: 0
})
const raw = toRaw(state)
raw.count++
state.count++
- markRaw 的不可逆性
const obj = markRaw({
count: 0
})
const state = reactive({
data: obj
})
state.data.count++
- 深层数据结构
const nested = reactive({
obj: markRaw({
count: 0,
deep: {
value: 1
}
})
})
nested.obj.count++
nested.obj.deep.value++
- 与 TypeScript 使用
interface RawObject {
count: number
nested: {
value: string
}
}
const obj = markRaw<RawObject>({
count: 0,
nested: {
value: 'hello'
}
})
const raw = toRaw(reactive(obj)) as RawObject