一、为什么我的数据总被“乱改”?
作为一名Vue开发者,你一定遇到过这样的尴尬场景:精心设计的数据结构,在某个不经意的时刻被同事(或者甚至是你自己)的代码意外修改,导致整个组件行为异常。排查这种问题往往耗时耗力,就像在茫茫代码海洋中寻找一根隐形的针。
想象一下这个场景:你开发了一个用户信息展示组件,接收一个user对象作为prop:
// 父组件
<template>
<UserProfile :user="userData" />
</template>
<script setup>
import { ref } from 'vue'
import UserProfile from './UserProfile.vue'
const userData = ref({
name: '张三',
age: 25,
profile: {
level: 'VIP',
points: 1000
}
})
</script>
在子组件中,本应只是展示数据,但某位粗心的开发者却这样写:
// 子组件 - 错误示例
<template>
<div>
<h1>{
{ user.name }}</h1>
<p>等级: {
{ user.profile.level }}</p>
<button @click="updateUser">错误操作</button>
</div>
</template>
<script setup>
const props = defineProps(['user'])
// 错误:直接修改了prop!
const updateUser = () => {
props.user.age = 30 // Vue会警告,但开发阶段可能被忽略
props.user.profile.points = 0 // 这甚至不会触发警告!
}
</script>
这种对props的直接修改在Vue中是被禁止的,但对于嵌套对象,Vue的警告机制并不完善。这就是readonly()大显身手的时候了!
二、readonly()是什么?Vue的"数据保镖"
简单来说,readonly()是Vue 3组合API中提供的一个方法,它接收一个响应式对象(无论是ref还是reactive),返回一个原对象的只读代理。任何尝试修改这个只读代理的操作都会在开发环境下触发警告,在生产环境下则静默失败。
import { reactive, readonly } from 'vue'
const original = reactive({
title: 'Vue3指南',
price: 99
})
const readOnlyCopy = readonly(original)
// 尝试修改只读对象
readOnlyCopy.price = 0 // 警告:Set operation on key "price" failed: target is readonly.
// 原始对象仍然可以修改
original.price = 79 // 这是允许的
readonly()的核心特点:
- 深度只读

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



