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>
相关推荐
帅帅哥的兜兜21 分钟前
next.js实现项目搭建
前端·react.js·next.js
筱歌儿26 分钟前
css 左右布局
前端·css
GISer_Jing1 小时前
编译原理AST&以Babel为例进行解读、Webpack中自定义loader与plugin
前端·webpack·node.js
GISer_Jing1 小时前
Webpack中Compiler详解以及自定义loader和plugin详解
前端·webpack·node.js
浩~~1 小时前
CSS常用选择器
前端·css
于慨1 小时前
uniapp+vite+cli模板引入tailwindcss
前端·uni-app
yunvwugua__1 小时前
Python训练营打卡 Day26
前端·javascript·python
满怀10152 小时前
【Django全栈开发实战】从零构建企业级Web应用
前端·python·django·orm·web开发·前后端分离
Darling02zjh2 小时前
GUI图形化演示
前端
Channing Lewis2 小时前
如何判断一个网站后端是用什么语言写的
前端·数据库·python