Vue组件之间的通信

一、通信方式

  • Props 和 Events :通过父组件传递 props 给子组件,子组件使用**$emit** 发送事件到父组件。
  • Event Bus:使用一个中央事件总线来跨组件通信。
  • Vuex:使用 Vuex 进行全局状态管理,以便在任何组件间共享状态。
  • Provide / Inject :祖先组件使用 provide 传递数据,后代组件通过 **inject**接收数据。
  • $refs :父组件通过 **ref**获取子组件实例,直接调用其方法或访问属性。
  • Scoped Slots:使用插槽在父组件中传递数据到子组件,允许子组件根据传递的数据进行渲染。

二、应用举例

1、Props 和 Events

父组件 (Parent.vue)

javascript 复制代码
<template>
  <Child :message="parentMessage" @update="handleUpdate" />
</template>
<script>
export default {
  data() {
    return { parentMessage: 'Hello from parent' };
  },
  methods: {
    handleUpdate(newMessage) {
      this.parentMessage = newMessage;
    }
  }
}
</script>

子组件 (Child.vue)

javascript 复制代码
<template>
  <button @click="updateParent">Update Parent</button>
</template>
<script>
export default {
  props: ['message'],
  methods: {
    updateParent() {
      this.$emit('update', 'Hello from child');
    }
  }
}
</script>

2、Event Bus

事件总线 (eventBus.js)

javascript 复制代码
import Vue from 'vue';
export const EventBus = new Vue();

发送消息 (ComponentA.vue)

javascript 复制代码
<template>
  <button @click="sendMessage">Send Message</button>
</template>
<script>
import { EventBus } from './eventBus';
export default {
  methods: {
    sendMessage() {
      EventBus.$emit('message', 'Hello from Component A');
    }
  }
}
</script>

接收消息 (ComponentB.vue)

javascript 复制代码
<template>
  <p>{{ receivedMessage }}</p>
</template>
<script>
import { EventBus } from './eventBus';
export default {
  data() {
    return { receivedMessage: '' };
  },
  created() {
    EventBus.$on('message', (message) => {
      this.receivedMessage = message;
    });
  }
}
</script>

3、Vuex

Vuex Store (store.js)

javascript 复制代码
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    message: 'Hello from Vuex'
  },
  mutations: {
    setMessage(state, newMessage) {
      state.message = newMessage;
    }
  }
});

更新消息 (ComponentA.vue)

javascript 复制代码
<template>
  <button @click="updateMessage">Update Message</button>
</template>
<script>
import { mapMutations } from 'vuex';
export default {
  methods: {
    ...mapMutations(['setMessage']),
    updateMessage() {
      this.setMessage('Hello from Component A');
    }
  }
}
</script>

显示消息 (ComponentB.vue)

javascript 复制代码
<template>
  <p>{{ message }}</p>
</template>
<script>
import { mapState } from 'vuex';
export default {
  computed: {
    ...mapState(['message'])
  }
}
</script>

4、Provide / Inject

提供数据 (Ancestor.vue)

javascript 复制代码
<template>
  <Descendant />
</template>
<script>
export default {
  provide() {
    return {
      message: 'Hello from ancestor'
    };
  }
}
</script>

注入数据 (Descendant.vue)

javascript 复制代码
<template>
  <p>{{ message }}</p>
</template>
<script>
export default {
  inject: ['message']
}
</script>

5、$refs

父组件 (Parent.vue)

javascript 复制代码
<template>
  <Child ref="childComponent" />
  <button @click="callChildMethod">Call Child Method</button>
</template>
<script>
import Child from './Child.vue';
export default {
  components: { Child },
  methods: {
    callChildMethod() {
      this.$refs.childComponent.someMethod();
    }
  }
}
</script>

子组件 (Child.vue)

javascript 复制代码
<template>
  <p>Child Component</p>
</template>
<script>
export default {
  methods: {
    someMethod() {
      console.log('Method in child called!');
    }
  }
}
</script>

6、Scoped Slots

父组件 (Parent.vue)

javascript 复制代码
<template>
  <Child>
    <template v-slot:default="slotProps">
      <p>{{ slotProps.message }}</p>
    </template>
  </Child>
</template>
<script>
import Child from './Child.vue';
export default {
  components: { Child }
}
</script>

子组件 (Child.vue)

javascript 复制代码
<template>
  <slot :message="'Hello from child'"></slot>
</template>
<script>
export default {}
</script>
相关推荐
爱勇宝8 小时前
大多数人不是在使用 AI 赚钱,而是在帮 AI 公司赚钱
前端·后端·程序员
冬奇Lab9 小时前
每日一个开源项目(第143篇):page-agent - 纯 JS 的网页 GUI Agent,无需截图、无需插件、无需后端
前端·人工智能·agent
To_OC11 小时前
LC 994 腐烂的橘子:人人都说是 BFS 入门题,我却写了三遍才过
javascript·算法·leetcode
IT_陈寒14 小时前
React的这个渲染问题连官方文档都没说清楚
前端·人工智能·后端
追逐时光者15 小时前
别再满网找零散工具了,腾讯 QQ 浏览器这个“帮小忙”工具箱真能省时间
前端·后端
如果超人不会飞15 小时前
脉络清晰的业务演进:TinyVue Timeline 时间线组件全方位实战指南
vue.js
如果超人不会飞15 小时前
从扁平到立体:掌握 TinyVue Grid 树形表格的高级实战指南
vue.js
To_OC17 小时前
LC 200 岛屿数量:经典 DFS 入门题,我第一次写居然连方向都搞错了
javascript·算法·leetcode
Asmewill17 小时前
grep&curl命令学习笔记
前端
stringwu17 小时前
Flutter 开发必备:MVI 架构的高效实现指南
前端·flutter