1.父子组件之间的传值:props
//父组件
<template>
<Message :msg="msg" />
</template>
<script setup>
import Message from "./Message.vue"
const msg= ref('给子组件的信息');
//const msg = reactive(["给子组件的信息"])
</script>
//Message子组件
<template>
<div></div>
</template>
<script setup>
//获取值 需要通过defineProps暴露出来
const props = defineProps({
msg: String,
//msg:{
//type:String,
//default:''
//}
});
console.log(props)
</script>
2.子组件向父组件传值emit
//父组件
<template>
<Message @getMsg="getmsg" />
</template>
<script setup>
import Message from "./Message.vue"
const getmsg = (msg)=>{
console.log(msg)
}
</script>
//Message子组件
<template>
<div @click="postMsg">向父组件传值</div>
</template>
<script setup>
const emit= defineEmits(["getMsg"])
const postMsg=()=>{
emit('getMsg','向父组件传值')
}
</script>
3.父组件获取子组件的属性或者调用子组件方法ref
//父组件
<template>
<Message ref="message" />
</template>
<script setup>
import Message from "./Message.vue"
const message= ref(null)
onMounted(() => {
console.log(message.value.msg)
message.value.showMsg()
});
</script>
//Message子组件
<template>
<div></div>
</template>
<script setup>
defineExpose({
msg:''子组件属性值'',
showMsg(){
console.log('子组件方法')
}
});
</script>
4.provide/inject 启用依赖注入 实现跨级访问祖先组件的数据
//父组件
<template>
<Message />
</template>
<script setup>
import Message from "./Message.vue"
import { provide } from "vue"
provide("msg", "父组件信息")
</script>
//Message子组件
<template>
<div></div>
</template>
<script setup>
import { inject } from 'vue';
let msg= ref()
msg= inject('msg') //接收参数
console.log(msg)
</script>
网友评论