defineExpose 子传父: 值、方法
介绍:提供方法给父组件调用
<template>
<div>
这里是父组件
<br />
<button @click="clickA">点击调用</button>
<son ref='sonref'></son>
</div>
</template>
<script setup>
import son from '@/views/demo/son.vue'
// components: {
// son
// }
const sonref = ref()
console.log(sonref, '打印sonref子组件实例')
const clickA = () => {
console.log(sonref.value.msg)
sonref.value.open11()
console.log('这里')
}
</script>
<style scoped lang=""></style>
<template>
<div>这里是子组件</div>
</template>
<script setup>
// 试验下子组件写方法让父组件使用
const open11 = () => {
console.log('子组件调用的open方法');
};
const msg = ref('你好啊');
defineExpose({ open11, msg });
</script>
<style scoped lang=""></style>
如果子组件通过 defineExpose
显式暴露了某个属性(如meg),父组件可以通过 ref
(即 sonref.value.msg
)直接访问和修改这个属性。这是 Vue 3 提供的一种 组件通信方式,但需要注意:数据需要是响应式的(如通过 ref
或 reactive
定义),并且这种行为会破坏单向数据流向,可能导致数据流难以追踪和维护,少用。
defineProps 父传子: 值
<template>
<div>
这里是父组件
<br />
<!-- <button >点击调用</button> -->
<son ref='sonref' :customerName="cName"></son>
</div>
</template>
<script setup>
import son from '@/views/demo/son.vue'
const cName = ref('小猪猪')
</script>
<style scoped lang=""></style>
<template>
<div>这里是子组件</div>
</template>
<script setup>
const props = defineProps(['customerName'])
onMounted(()=>{
console.log(props.customerName, '打印父组件的值')
})
</script>
<style scoped lang=""></style>
defineEmits: 子传父 (vue2的emit。。)
介绍: 调用父组件的方法并传参
<template>
<div>
这里是父组件
<br />
<son ref='sonref' @getData="getFatherData" ></son>
</div>
</template>
<script setup>
import son from '@/views/demo/son.vue'
const getFatherData = (dataName) => {
console.log(dataName, '子组件调父组件方法并传的值')
}
</script>
<style scoped lang=""></style>
<template>
<div>这里是子组件</div>
<button @click="btnClick">点击调用父组件方法并传参</button>
</template>
<script setup>
let emits = defineEmits([`getData`])
const btnClick = () => {
emits(`getData`, '成毅')
}
</script>
<style scoped lang=""></style>