1. From father to son (prop)
1. Parent component: cc.vue
<template>
<div>
<h2>组件通信的几种方式</h2>
<div class="fatherOne">
<div>
<ccSonOne :msg2=msg2></ccSonOne>a
</div>
</div>
</div>
</template>
<script setup>
import {ref} from "vue"
import ccSonOne from "../components/ccSonOne.vue"
const msg2 = ref("我是父亲")
</script>
2. Subcomponent: ccSonOne.vue
<template>
<div>
<span>我是c页面的一个儿子,我接受到父亲的动态值为:{
{msg2}}</span>
</div>
</template>
<script setup>
const props = defineProps({
msg2:{
type:String,
default:"hh"
}
})
</script>
3. Effect:
2: Child Father
1. Parent component: cc.vue
<template>
<div>
<h2>组件通信的几种方式</h2>
<div class="fatherOne">
<div>
<ccSonOne @sonData="getmsg" ></ccSonOne>
<span>儿子传递过来的值:{
{getData}}</span>
</div>
</div>
</div>
</template>
<script setup>
import {ref} from "vue"
import ccSonOne from "../components/ccSonOne.vue"
const getData = ref("2")
const getmsg = (sonData) => {
getData.value = sonData
}
</script>
2. Subcomponent: ccSonOne.vue
<template>
<div>
<button @click="sendmsg">点我给父亲传值</button>
</div>
</template>
<script setup>
import {ref} from "vue"
const msg = ref("我是儿子")
const emit = defineEmits(['sonData'])
const sendmsg = () => {
emit("sonData", msg.value)
}
</script>
3. Effect:
Before clicking:
After clicking:
3. expose, ref (obtain sub-component properties and methods)
1.cc.vue
<template>
<div>
<h2>组件通信的几种方式</h2>
<div class="fatherOne">
<div>
<ccSonOne ref="comp"></ccSonOne>
<button @click="getAttribute">点击获取子组件的属性和方法</button>
<br>
<span>{
{getAttributeData}}</span>
</div>
</div>
</div>
</template>
<script setup>
import {ref} from "vue"
import ccSonOne from "../components/ccSonOne.vue"
const comp = ref(null)
const getAttributeData = ref("")
const getAttribute = () => {
getAttributeData.value=comp.value.attributeone,
comp.value.functionOne()
}
</script>
2.ccSonOne.vue
<template>
<div>
</div>
</template>
<script setup>
import {ref} from "vue"
const attributeone = ref("我是子组件属性")
const functionOne = () =>{
console.log("我是子组件方法")
}
defineExpose({
attributeone:attributeone.value,
functionOne,
})
</script>
3. Effect: