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>
相关推荐
excel13 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel15 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼16 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping16 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙17 小时前
[译] Composition in CSS
前端·css
白水清风17 小时前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix17 小时前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户221520442780017 小时前
new、原型和原型链浅析
前端·javascript
阿星做前端17 小时前
coze源码解读: space develop 页面
前端·javascript
叫我小窝吧17 小时前
Promise 的使用
前端·javascript