当前位置:  首页>> 技术小册>> Vue面试指南

在Vue中,组件之间有多种通信方式,下面列举其中的几种:

父子组件通信:通过props和$emit实现。父组件通过props向子组件传递数据,子组件通过$emit触发事件并传递数据给父组件。

父组件代码:

  1. <template>
  2. <div>
  3. <child :message="parentMessage" @child-event="handleChildEvent"></child>
  4. </div>
  5. </template>
  6. <script>
  7. import Child from './Child.vue'
  8. export default {
  9. components: {
  10. Child
  11. },
  12. data() {
  13. return {
  14. parentMessage: 'Hello from parent'
  15. }
  16. },
  17. methods: {
  18. handleChildEvent(message) {
  19. console.log(message)
  20. }
  21. }
  22. }
  23. </script>

子组件代码:

  1. <template>
  2. <div>
  3. <button @click="handleClick">Send Message to Parent</button>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. props: {
  9. message: String
  10. },
  11. methods: {
  12. handleClick() {
  13. this.$emit('child-event', 'Hello from child')
  14. }
  15. }
  16. }
  17. </script>

子父组件通信:通过$emit和$parent实现。子组件通过$emit触发事件并传递数据给父组件,父组件通过$parent访问子组件实例并调用其方法。

父组件代码:

  1. <template>
  2. <div>
  3. <child ref="child"></child>
  4. <button @click="handleClick">Call Child Method</button>
  5. </div>
  6. </template>
  7. <script>
  8. import Child from './Child.vue'
  9. export default {
  10. components: {
  11. Child
  12. },
  13. methods: {
  14. handleClick() {
  15. this.$refs.child.childMethod('Hello from parent')
  16. }
  17. }
  18. }
  19. </script>

子组件代码:

  1. <template>
  2. <div>
  3. </div>
  4. </template>
  5. <script>
  6. export default {
  7. methods: {
  8. childMethod(message) {
  9. console.log(message)
  10. }
  11. }
  12. }
  13. </script>

兄弟组件通信:通过一个空的Vue实例作为中央事件总线(event bus)实现。兄弟组件都引入该实例,一个组件通过事件触发器向实例发布事件,另一个组件通过事件监听器接收并响应该事件。

中央事件总线代码:

  1. import Vue from 'vue'
  2. export const bus = new Vue()

兄弟组件代码:

  1. <template>
  2. <div>
  3. <button @click="handleClick">Send Message to Brother</button>
  4. </div>
  5. </template>
  6. <script>
  7. import { bus } from './bus'
  8. export default {
  9. methods: {
  10. handleClick() {
  11. bus.$emit('brother-event', 'Hello from brother A')
  12. }
  13. }
  14. }
  15. </script>

该分类下的相关小册推荐: