# Vue组件通信方式

# 1. props

<!-- Parent  -->
<child :msg="msg"></child>
<script setup>
import { ref } from "vue";
import child from "./child.vue";
const msg = ref("这是传给子组件的信息");
</script>

<!-- Child -->
<script setup>
// 不需要引入 defineProps 直接使用
const props = defineProps({
  msg: String,
});
console.log(props); // { msg: "这是传给子组件的信息" }
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 2. emit

<!--  Child 派发 -->
<template>
  <button @click="handleClick">按钮</button>
</template>
<script setup>
// 方适用于Vue3.2版本 不需要引入 defineEmits
const emit = defineEmits(['myClick']);
const handleClick = () => {
  emit('myClick', '这是发送给父组件的信息');
};
</script>

<!-- Parent 响应 -->
<template>
  <child @myClick="onMyClick"></child>
</template>
<script setup>
import child from "./child.vue";
const onMyClick = (msg) => {
  console.log(msg); // 这是父组件收到的信息
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# 3. expose / ref

<!--  Child -->
<script setup>
import { ref } from 'vue';
const name = ref('test');
const change = (data) => {
  name.value = data;
};
defineExpose({
  name,
  change
});
</script>

<!-- Parent -->
<template>
  <child ref="comp" ></child>
  <button @click="handlerClick">按钮</button>
</template>
<script setup>
import child from "./child.vue";
const handlerClick = (msg) => {
  console.log(comp.value.name); // test 获取子组件对外暴露的属性
  comp.value.change('test1'); // 调用子组件对外暴露的方法
  console.log(comp.value.name); // test1 获取子组件对外暴露的属性
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# 4. $attrs

<!-- Parent -->
<template>
  <child ref="comp" :msg="msg" title="test"></child>
</template>
<script setup>
import { ref } from 'vue';
import child from "./child.vue";
const msg = ref('这是传给子组件的信息');
</script>
<!--  Child -->
<script setup>
import { useAttrs } from 'vue';
const attrs = useAttrs();
console.log('attrs', attrs); // { msg: "这是传给子组件的信息", test: "test" }
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 5. v-model

可以支持多个数据双向绑定

<!-- Parent -->
<child v-model:key="key" v-model:value="value"></child>
<script setup>
import { ref, reactive } from "vue";
import child from "./child.vue";

const key = ref("1111");
const value = ref("2222");
</script>

<!-- Child -->
<template>
  <button @click="handlerClick">按钮</button>
</template>
<script setup>
const emit = defineEmits(["key", "value"]);
const handlerClick = () => {
  emit("update:key", "新的key");
  emit("update:value", "新的value");
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 6. provide / inject

provide / inject 为依赖注入

provide:可以让我们指定想要提供给后代组件的数据或

inject:在任何后代组件中接收想要添加在这个组件上的数据,不管组件嵌套多深都可以直接拿来用

<!-- Parent -->
<script setup>
import { provide } from "vue";
provide("name", "沐华");
</script>

<!-- Son -->
<script setup>
import { inject } from "vue";
const name = inject("name");
console.log(name); // 沐华
</script>
1
2
3
4
5
6
7
8
9
10
11
12

如果provide的key有多个父组件提供,那么孙子组件会取离他最近的父组件的所提供的key的值

# 7. Vuex/Pinia

后续单独讲

Last Updated: 3/11/2025, 11:18:52 AM