Vue3组件封装—setup语法糖中使用defineProps

1,039 阅读1分钟

父组件:

<Child :detailInfo="xxx"/>

Child组件内接受props

<script setup lang="ts">
  
import {defineProps} from 'vue'; // 引入defineProps
const props = defineProps<{detailInfo: any}>(); // defineProps的类型一定是:<{ 父组件传的变量名: 类型 }>
console.log(props.detailInfo); // defineProps返回的props是一个Proxy代理对象,可以理解为父组件传来的所有变量都是作为这个对象的属性,所以通过props.<父组件传的变量名>来访问具体的数据;
​
</script>

但是不能对defineProps<{detailInfo: any}>()的返回值进行解构:

<script setup lang="ts">
  
import {defineProps} from 'vue';
const {detailInfo} = defineProps<{detailInfo: any}>(); // 报错
console.log(detailInfo); 
​
</script>

会报错:

error  Destructuring the `props` will cause the value to lose reactivity  vue/no-setup-props-destructure

也就是说解构会使props中的数据失去响应式,即父组件传值变化而子组件不会更新。