vue3父子组件传值,子组件暴漏方法

1.父传子 defineProps

父组件直接通过属性绑定的方式给子组件绑定数据,子组件通过defineProps接收函数接收


其中v-model是完成事件绑定和事件监听的语法糖。v-model算是v-bindv-on的简洁写法,等价于

<c-input ref="inputRef" :modelValue="inputValue" @input="inputValue = $event.target.value"></c-input>

子组件接收:

子组件使用:props.modelValue

2.子传父 defineEmits

子组件通过defineEmits注册一个自定义事件,而后触发emit去调用该自定义事件,并传递参数给父组件。

在父组件中调用子组件时,通过v-on绑定一个函数,通过该函数获取传过来的值。

父组件传值:

子组件接收:

3.子组件暴漏方法,父组件调用 defineExpose

(1)在父组件中获取在子组件的实例

(2)在子组件中通过defineExpose暴漏方法

子组件:

父组件:

4.完整代码

复制代码
//父:
<template>
  <h2>父组件:{{ inputValue }}</h2>
  <CInput ref="inputRef"  v-model:modelValue="inputValue"></CInput>
  <!-- <c-input ref="inputRef" :modelValue="inputValue" @input="inputValue = $event.target.value"></c-input> -->
  <button @click="submitForm">提交</button>
  <span v-if="errorMessage" style="color:red">{{ errorMessage }}</span>
</template>
<script setup>
//在vue3中如何将子组件的方法暴漏
//1.在父组件中获取在子组件的实例
//2.在子组件中通过defineExpose暴漏方法
import { ref } from 'vue'
import CInput from '@/views/CInput.vue'

const inputValue = ref('')
const errorMessage = ref('')
const inputRef = ref(null)
const submitForm = () => {
  if(inputRef.value.validate(inputValue.value)){
    errorMessage.value=''
  } else {
    errorMessage.value='输入不能为空'
  }
}
</script>
子:
<template>
  <!-- @input是一个常用的指令,用于监听原生input事件。当输入框的值发生变化时,@input指令绑定的方法会被触发。 -->
  <input 
    type="text" 
    :value="modelValue" 
    @input="updateValue"/>

</template>
<script setup>
import { defineProps,defineEmits,defineExpose } from 'vue'

const props= defineProps({
  modelValue:{
    type:Number
    //require:true
  }
})
const emit = defineEmits(['update:modelValue'])
//const emit = defineEmits([modelValue'])
const updateValue = (event) =>{
  emit('update:modelValue',event.target.value)
}
const validate = (value)=>{
//简单校验规则,输入不能为空
  return value.trim()!==''
}
//暴漏方法
defineExpose({
  validate 
})
</script>
相关推荐
Ulyanov24 分钟前
《PySide6 GUI开发指南:QML核心与实践》 第二篇:QML语法精要——构建声明式UI的基础
java·开发语言·javascript·python·ui·gui·雷达电子对抗系统仿真
聚美智数1 小时前
企业实际控制人查询-公司实控人查询
android·java·javascript
SoaringHeart1 小时前
Flutter进阶:用OverlayEntry 实现所有弹窗效果
前端·flutter
IT_陈寒3 小时前
Vite静态资源加载把我坑惨了
前端·人工智能·后端
herinspace3 小时前
管家婆实用贴-如何分离和附加数据库
开发语言·前端·javascript·数据库·语音识别
小码哥_常3 小时前
从MVC到MVI:一文吃透架构模式进化史
前端
嗷o嗷o3 小时前
Android BLE 的 notify 和 indicate 到底有什么区别
前端
豹哥学前端4 小时前
别再背“var 提升,let/const 不提升”了:揭开暂时性死区的真实面目
前端·面试
Lkstar4 小时前
我把Vue2响应式源码从头到尾啃了一遍,这是整理笔记
vue.js
lar_slw4 小时前
k8s部署前端项目
前端·容器·kubernetes