defineProps解构引发的疑问???

598 阅读1分钟

解构有效

当我直接解构defineProps里面的东西的时候

// father
const str = ref("这是一个字符串");
const obj = reactive({
  counts: 1,
  person: {
    name: "Tom",
    age: 18,
  },
});
setTimeout(() => {
  str.value = '响应式还在'
  obj.counts++
}, 1000);

// Children
const {data,str} = defineProps({
  data:{
    type:Object,
    default:()=>{}
  },
  str:{
    type:String,
    default:''
  }
})
  • 此时我发现不管父组件怎么改变当前得值,子组件都是同步得

仅对传递得引用类型有效

// father
const str = ref("这是一个字符串");
const Dog = ref({name:'旺财'})
const obj = reactive({
  counts: 1,
  person: {
    name: "Tom",
    age: 18,
  },
});

setTimeout(() => {
  str.value = '失去响应式'
  Dog.value.name = '啊黄'
  obj.counts++
}, 1000);

// Chilren
const props = defineProps({
  data: {
    type: Object,
    default: () => {},
  },
  str: {
    type: String,
    default: "",
  },
  Dog: {
    type: Object,
    default: () => {},
  },
});
const { data, str, Dog } = props;
  • 此时str失去响应式

疑惑,为什么网上都说defineProps解构会失去响应式