本文最后更新于:2024年4月25日 上午
父组件传子组件
props
📌父组件
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.$props
和this
对象中均会获得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
📌父组件
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> <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) } } } </script>
<template> <div class="container"> <input v-model="inputTitle"/> <button @click="sendTitle">更新标题</button> </div> </template>
|