踩了很多坑,现在来做个记录,希望看到这篇博客的小伙伴能够避免踩坑
首先父组件传子组件:还是使用v-bind传,然后子组件使用就不一样了
<!-- 父组件 -->
<template>
<!-- 子组件 -->
<hello ref="childrenRef" :mess="msg"></hello>
</template>
<script setup>
import {ref } from 'vue'
import hello from "./子组件.vue"
let msg = ref("我是要传的数据")
</script>
<!-- 子组件 -->
<template>
{{mess}}
</template>
<script setup>
const props = defineProps ({
mess:String
})
</script>
然后,父组件要拿到子组件定义的数据,或者触发子组件的方法,要在子组件标签上写ref=“xxxx”,但是在子组件定义的数据和方法一定要使用defineExpose({ msg,fun });暴露出来
<!-- 父组件 -->
<template>
<!-- 子组件 -->
<hello ref="childrenRef"></hello>
</template>
<script setup>
import {ref,onMounted } from 'vue'
import hello from "./子组件.vue"
const childrenRef = ref(null)
onMounted(()=>{
// 打印出子组件数据
console.log(childrenRef.value.message)
// 执行子组件的方法
childrenRef.value.fun()
})
</script>
<!-- 子组件 -->
<template>
{{message}}
</template>
<script setup>
import {ref} from 'vue'
const message = ref('我是子组件数据')
const fun = () => {
console.log("我是子组件的方法")
}
defineExpose({ message,fun })
</script>
子组件给父组件传值或者触发父组件方法,要使用自定义事件,
<!-- 父组件 -->
<template>
<!-- 子组件 -->
<hello @pageFn = "pageFn"></hello>
</template>
<script setup>
import {ref,onMounted } from 'vue'
import hello from "./子组件.vue"
const pageFn = (msg) => {
console.log(msg)
}
</script>
<!-- 子组件 -->
<template>
<button @click="seedMsg">子组件按钮</button>
</template>
<script setup>
import {ref} from 'vue'
const emit = defineEmits(["pageFn"]); //定义一个变量来接收父组件传来的方法
let msg = ref('我是要传递的数据')
const seedMsg = () =>{
emit('pageFn',msg)
}
</script>