vue3 Props的使用
Props是什么?
官方地址:Props | Vue.js
在 Vue 中,props
是父组件向子组件传递数据的一种机制。
props
是子组件中定义的自定义属性,父组件通过这些属性向子组件传递数据。
它们是单向数据流的一部分,意味着数据只能从父组件流向子组件,而不能反过来。
定义props
在子组件中,可以通过 props
选项来定义接收的属性。props
可以是数组或对象形式。
子组件 child.vue
在使用 <script setup>
的单文件组件中,props 可以使用 defineProps()
宏来声明:
<script setup> const props = defineProps(['foo']) console.log(props.foo) </script>
除了使用字符串数组来声明 props 外,还可以使用对象的形式:
<script setup> const props = defineProps({ title: String, likes: Number }) console.log(props.foo) </script>
对于以对象形式声明的每个属性,key 是 prop 的名称,而值则是该 prop 预期类型的构造函数。比如,如果要求一个 prop 的值是 number
类型,则可使用 Number
构造函数作为其声明的值。
对象形式的 props 声明不仅可以一定程度上作为组件的文档,而且如果其他开发者在使用你的组件时传递了错误的类型,也会在浏览器控制台中抛出警告。
监听props 自定义属性
child.vue 子组件
<script setup> import { ref } from 'vue' import { watchEffect,watch } from 'vue' //自定义属性 const props = defineProps(['name','age']); //监听自定义属性 watch(() => props.name,(newVal,oldVal) => { console.log("----监听name---- newVal:" + newVal,"oldVal:" + oldVal); }) watch(() => props.age,(newVal,oldVal) => { console.log("----监听age---- newVal:" + newVal,"oldVal:" + oldVal); }) </script>