登录  /  注册
博主信息
博文 70
粉丝 0
评论 2
访问量 90329
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
VUE3组合式API setup语法糖 父组件与子组件的传值方式
搁浅
原创
651人浏览过

父组件

  1. <template>
  2. <zhapi
  3. :name="content"<!-- 传给子组件的值 --><!-- -->
  4. :fun="funzi"<!-- 可以把函数传给子组件使用 -->
  5. ref="showInfoRef"<!-- 父组件给子组件色值别名showInfoRef -->
  6. @handLer="hand"<!-- handLer子组件自定义的事件,hand是父组件的function,子传父内容 -->
  7. >
  8. <template
  9. v-slot:sl<!-- 插槽插入 -->
  10. #sl<!-- 插槽插入简写 -->
  11. >
  12. <div>插槽item内容<img src="#" /></div>
  13. </template>
  14. </zhapi>
  15. <button @click="funzi"></button>
  16. </template>
  17. <script setup>
  18. import {ref,provide} from 'vue';
  19. const showInfoRef = ref()
  20. const content = ref('张张')
  21. //把name提供出去,下面所有层级组件接收注入,如子组件、孙子组件,都接收依赖注入。
  22. provide("name", name);
  23. function funzi(){
  24. showInfoRef.value.zi()//父组件调用子组件的方法
  25. }
  26. function hand(e){
  27. console.log(e)//e是子组件传过来的数据
  28. }
  29. <script>

子组件

  1. <template>
  2. <div>父组件传过来的值:{{props.name}}</div>
  3. <button @click="expose">子组件暴露给父组件使用</button>
  4. <button @click="zifu">子传父</button>
  5. <slot name="sl"></slot>//插槽
  6. </template>
  7. <script setup>
  8. import {ref,inject} from 'vue';
  9. const name = inject("name");//接收依赖注入
  10. const props = defineProps({//子组件接收父组件传的值
  11. name: {
  12. type: String,//数据类型,数据类型传错了,会报错提示。
  13. default: "张张",//默认值
  14. required: true,//当前属性必传,不传也能运行,会报错提示。
  15. },
  16. age: {
  17. type: Number,
  18. default: 0
  19. },
  20. arr:{
  21. type:Array,
  22. default:[]
  23. },
  24. fun:{
  25. type:Function
  26. },
  27. })
  28. const ArrayList = reactive([
  29. {
  30. id: 1,
  31. name: "法外",
  32. },
  33. {
  34. id: 2,
  35. name: "狂徒",
  36. }
  37. ]);
  38. function zi(){
  39. console.log('父组件直接使用子方法')
  40. }
  41. const emits = defineEmits(["handLer"]);//使用defineEmits语法糖的方法来创建自定义事件。
  42. function zifu(){//子组件传值给父组件
  43. emits("handLer", ArrayList);//左边是你的自定义事件名,右边是你要传的数据。
  44. };
  45. function expose(){
  46. console.log(props.name)
  47. }
  48. // 把expose函数或者ArrayList值暴露出去给父组件使用,所有父组件要使用的数据,必须在这里暴露出去。
  49. defineExpose({
  50. expose,
  51. ArrayList
  52. })
  53. <script>
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学