Vue组件通信

本文最后更新于:2023年7月28日 凌晨

以下内容适用于Vue2.x

父组件传子组件

props

官方文档: 🔗props (vuejs.org)

📌父组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script>
import SonProps from 'xxx'

export default {
component: {
SonProps,
}
}
</script>

<template>
<div>
<SonProps title="Props通信" articleId="999"/>
</div>
</template>

📌子组件

this.$propsthis对象中均会获得props

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script>
export default {
props: {
title: {
type: String,
default: 'NULL'
},
articleId: {
type: Number,
default: 0
}
}
}
</script>

<template>
<h1>{{ articleId }} - {{ title }}</h1>
</template>

Provide/Inject

📌父组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script>
import SonInject from 'xxx'

export default {
components: {
SonInject,
},
provide: {
title: 'Provied/Inject',
articleId: 2
}
};
</script>

<template>
<div id="app">
<SonInject />
</div>
</template>

📌子组件

1
2
3
4
5
6
7
8
9
10
11
12
<script>
export default {
inject: ['title', 'articleId']
}
</script>

<template>
<div>
<h1>{{ title }}</h1>
<h2>{{ articleId }}</h2>
</div>
</template>

子组件传父组件

emit

官方文档: 🔗$emit (vuejs.org)

📌父组件

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
27
28
29
30
31
<script>
import SonEmit from "./components/children/SonEmit.vue";

export default {
components: {
SonEmit,
},
data() {
return {
title: "$emit通信",
};
},
methods: {
updateTitle(newTitle) {
this.title = newTitle
},
}
};
</script>

<template>
<div id="app">
<SonProps title="props" articleId="1" />
<SonInject />
<div class="emitBox">
<h1>{{ title }}</h1>
<!-- 触发`acceptTitle`事件后调用`updateTitle`方法更新 -->
<SonEmit @acceptTitle="updateTitle" />
</div>
</div>
</template>

📌子组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script>
export default {
data () {
return {
inputTitle: ''
}
},
methods: {
sendTitle () {
this.$emit('acceptTitle', this.inputTitle) // 触发自定义事件`acceptTitle`
}
}
}

</script>

<template>
<div class="container">
<input v-model="inputTitle"/>
<button @click="sendTitle">更新标题</button>
</div>
</template>

Vue组件通信
https://qingshaner.com/vue组件通信/
作者
清山
发布于
2022年3月3日
许可协议