父传子-defineProps函数
步骤:
- 父组件提供数据
- 父组件将数据传递给子组件
- 子组件通过
defineProps
进行接收 - 子组件渲染父组件传递的数据
//父组件 //父组件向子组件提供a,b两个变量 <template> <div> <son :a="1" :b="num"></son> </div> </template> <script setup> import son from './components/sondefineProps.vue' import {ref} from 'vue' const num = ref(666) </script> <style> </style>
//子组件使用defineProps接收父组件传来的a,b两个变量 <template> <div> <div> {{ a }}==={{ b }} </div> </div> </template> <script setup> const obj= defineProps({ a:{ type:String }, b:Number }) console.log(obj,'父传子'); </script> <style> </style>
- 如果使用
defineProps
接收数据,这个数据只能在模板中渲染 - 如果想要在
script
中也操作props
属性,应该接收返回值
子传父-defineEmits函数
步骤:
- 子组件通过
defineEmits
获取emit
函数(因为没有this) - 子组件通过
emit
触发事件,并且传递数据 - 父组件提供方法
- 父组件通过自定义事件的方式给子组件注册事件
//父组件 //父组件提供一个方法sonhandle,供子组件绑定,父组件通过这个方 //法绑定一个事件fatherget来接收子组件传过来的值(使用形参接收) <template> <div> <son @sonhandle="fatherget"></son> </div> </template> <script setup> import son from './components/sondefineEmits.vue' const fatherget = (e)=>{ console.log('父组件','fatherget',e); } </script> <style> </style>
//子组件通过按钮事件触发组件传值,通过defineEmits()这个方法找到父组件 //提供的事件(获取 emit 函数(因为没有this)),并通过emit函数触发事件, //传递信息 <template> <div> 子传父123 <button @click="btn">按钮</button> </div> </template> <script setup> const fater = defineEmits(['sonhandle']) const btn = ()=>{ fater('sonhandle','子向父传的值') } </script> <style lang='less' scoped> </style>