你说一下vue是如何实现组件通信的?
1.父传子
基本思想
- 父组件中给子组件绑定属性
- 子组件内部通过props选项接收数据
以下是父组件给子组件传递的非响应式数据,直接在子组件身上
// 引入子组件
import sonIndex from "./components/sonIndex.vue";
</script>
<template>
<div ref="h1Ref" class="father">
父组件的count--{{ count }}
<sonIndex message="父组件向子组件传值" @updataCount="updata"/>
</div>
</template>
之后子组件通过props接收
<template>
<div class="son">我是子组件
<h3>父组件传过来的数据--{{ props.message }}</h3>
</div>
</template>
<script setup>
import { defineProps } from "vue";
const props = defineProps({
message: String,
});
</script>
在页面上的呈现
接下来是父组件向子组件传递响应式数据,这很简单,在绑定数据的前面加上:就行,子组件以同样的方式接收
import sonIndex from "./components/sonIndex.vue";
const count = ref(0);
const updata = () => {
count.value++
}
</script>
<template>
<div ref="h1Ref" class="father">
我是父组件的count--{{ count }}
<sonIndex :count="count" @updataCount="updata"/>
<button @click="updata">++</button>
</div>
</template>
<template>
<div class="son">我是子组件
<h3>父组件传过来的数据--{{ props.count }}</h3>
</div>
</template>
<script setup>
import { defineProps } from "vue";
const props = defineProps({
count: Number,
});
</script>
2.子传父
基本思想
- 父组件中给子组件标签通过@绑定事件
- 子组件内部通过 emit 方法触发事件
以下是一个好理解的例子,父组件定义一个响应式数500并传给子组件,父组件的方法有getMoney赚钱,每次赚200,而子组件就是通知父组件花钱,每次花50。