Vue3进阶<3>defineEmits update:子组件向父组件事件传递和父子组件之间的双向数据绑定
常用的子组件向父组件传递事件
子组件代码:
<template>
<div class="child-con">
<p>我是子组件2</p>
<button @click="toParentEmits">点击传到父组件</button>
</div>
</template>
<script setup lang="ts">
import {ref,defineEmits} from "vue";
//第一步先定义
const childValue = ref("我是子组件的值childValue")
const emits = defineEmits(['getChild']);
const toParentEmits = () =>{
//第二步发送值
emits('getChild',childValue)
}
</script>
<style scoped>
</style>
父组件代码:
<template>
<div>
<p>我是父组件1</p>
<!-- 第一步定义一个事件,去接收子组件的getChild-->
<Child @getChild="getChild"></Child>
{{state}}
</div>
</template>
<script setup lang="ts">
import Child from "./components/child6.vue"
import {ref} from "vue";
//第二不定义一个空值接收子组件传来的值
let state = ref(null)
const getChild = (childValue) =>{
state.value = childValue
}
</script>
<style scoped>
</style>
效果
defineEmits update:用法
在Vue 3中,emit('update:modelValue')
的作用是触发一个名为update:modelValue
的自定义事件。这个事件通常用于实现父子组件之间的双向数据绑定。
子组件接收父组件传过来的值 然后通过computed get set 去改变,然后触发update:modelValue
自定义事件,去改变父组件的值 这样子父组件就双向绑定了
父组件
<template>
<div class="demo">
<p>我是父组件1</p>
<!-- 第一步定义一个事件,去接收子组件的getChild-->
<br>
<Child v-model:name="name" v-model:age="age" @getChild="getChild"></Child>
<br>
{{state}}
<br>
<h1>父组件名字: {{ name }}</h1>
<h1>父组件年龄: {{ age }}</h1>
</div>
</template>
<script setup lang="ts">
import Child from "./components/child6.vue"
import {ref} from "vue";
//第二不定义一个空值接收子组件传来的值
const state = ref(null)
const name = ref(null);
const age = ref(null);
const getChild = (childValue) =>{
state.value = childValue
}
</script
父组件
<template>
<div class="child-con">
<p>我是子组件2</p>
<button @click="toParentEmits">点击传到父组件</button><br>
子组件输入框name<input v-model="name" placeholder="输入姓名" @input="changeName(name)" />
子组件输入框age<input v-model="age" placeholder="输入姓名" @input="changeAge(age)" />
</div>
</template>
<script setup lang="ts">
import {ref,defineEmits,computed } from "vue";
//第一步先定义
const childValue = ref("我是子组件的值childValue")
const emits = defineEmits(['update:name','update:age','getChild']);
const props = defineProps({
name: { type: String, default: "张三" },
age: { type: Number, default: 18 }
})
const name = computed({
get: () => props.name,
set: (val) => {
emits('update:name', val)
}
})
const age = computed({
get: () => props.age,
set: (val) => {
emits('update:age', val)
}
})
// 数据双向绑定
const changeName = (val) => {
emits('update:name', val)
}
const changeAge = (val) => {
emits('update:age', val)
}
const toParentEmits = () =>{
//第二步发送值
emits('getChild',childValue)
}
</script>
效果可以看到在子组件输入框改变name和age 父组件也时时变化了