大飞_dafei

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

Vue3中常见传值方式

Vue3中常见传值方式

Props 方式

复制代码
<template>
  <!-- 父组件-->
  <Bar :msg="'prop传值'"/>
</template>

<script setup>
  import Bar from './bar.vue'
</script>

------------------------------------
<template>
  <!-- 子组件 -->
  <h1>{{ msg }}</h1>

  <button type="button" @click="count++">
    fei 数量 {{ count }}
  </button>

</template>

<script setup>
  import { ref } from 'vue'
  defineProps({msg: String})
  const count = ref(0)
</script>
View Code
复制代码

 

 

Emits 方式

复制代码
<template>
  <!-- 父组件-->
  <Bar @add="handleFei"/>
</template>

<script setup>
  import Bar from './bar.vue'
  const handleFei = (value) => {
    console.log("接受参数:", value);
  }
</script>

------------------------------------
<template>
  <!-- 子组件 -->
  <button @click="feiClick">点击我触发emits</button>
</template>

<script setup>
  import { defineEmits  } from 'vue'
  const emits = defineEmits(['add'])
  const feiClick = () => {
    emits("add","我是参数,传给父组件")
  }
</script>
View Code
复制代码

 

DefineExpose 父调子

复制代码
<template>
  <!-- 父组件-->
  <button @click="feiClick" >点击我触发emits</button>
  <Bar ref="feiRef"/>
</template>

<script setup>
  import Bar from './bar.vue'
  import {ref} from "vue";
  const feiRef = ref(null);
  const feiClick = () => {
    // 调用子组件
    feiRef.value.childrenFei();
  }
</script>

------------------------------------
<template>
  <!-- 子组件 -->
</template>
<script setup>
 const childrenFei = () => {
   console.log("接受父组件方法");
 }
 // 暴露出去方法,让父组件调用
 defineExpose({
   childrenFei
 })
</script>
View Code
复制代码

 

Provide/Inject 隔代传递

复制代码
<template>
  <!-- 父组件-->
  <Bar />
</template>

<script setup>
  import Bar from './bar.vue'
  import {provide} from "vue";
  provide('list',"可以隔代传给子组件")
</script>

------------------------------------
<template>
  <!-- 子组件 -->Provide/Inject
  <p>{{fei}}</p>
</template>
<script setup>
  import {inject} from "vue";
  const fei = inject("list")
</script>
View Code
复制代码

 

 

 

 

 

 

posted on   大飞_dafei  阅读(668)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2019-02-25 这家伙有点懒,还没有个性签名 :) -- 参考网站学习篇01
点击右上角即可分享
微信分享提示