一、父子通信props

适用于父子组件的通信

子组件:Son.vue

  1. ...
  2. <h2>子组件</h2>
  3. <!-- 直接在html标签中,自定义sonClick事件,并向传递arg参数 -->
  4. <button @click="$emit('sonClick','arg')">子组件按钮</button>
  5. ...
  6. -------另一种写法------
  7. ...
  8. <h2>子组件</h2>
  9. <!-- 监听点击,在methods中处理 -->
  10. <button @click="toFather">子组件按钮</button>
  11. ...
  12. <script>
  13. export default {
  14. name: "GrandSon",
  15. methods: {
  16. toFather() {
  17. // 自定义sonClick事件,并向传递参数'arg'
  18. this.$emit("sonClick", "arg");
  19. },
  20. },
  21. };
  22. </script>

父组件:Father.vue

  1. ...
  2. <h2>父组件</h2>
  3. <!-- 监听子组件的自定义事件,并在sonClick方法中处理 -->
  4. <Son @sonClick="handleSonClick" />
  5. ...
  6. <script>
  7. import Son from "./Son.vue";
  8. export default {
  9. components: { Son },
  10. name: "Father",
  11. methods: {
  12. handleSonClick(arg) {
  13. console.log(arg); //arg
  14. },
  15. },
  16. };
  17. </script>

二、祖孙通信

适用于祖孙之间的通信

孙子组件:GrandSon.vue

  1. ...
  2. <h2>孙子组件</h2>
  3. <!-- 监听点击,自定义grandSonClick,并传递arg参数 -->
  4. <button @click="$emit('grandSonClick','arg')">孙子组件按钮</button>
  5. ...

儿子组件:Son.vue

  1. ...
  2. <h2>父组件</h2>
  3. <!-- 获取父组件的自定义事件,并向下监听,这样爷爷组件就可以监听到孙子组件的事件-->
  4. <grand-son v-on="$listeners" />
  5. 等同于:
  6. <grand-son @grandSonClick="$emit('grandSonClick',arg)" />
  7. ...

爷爷组件:GrandFather.vue

  1. ...
  2. <h2>爷爷组件</h2>
  3. <!-- 监听孙子组件的自定义事件,并处理 -->
  4. <Son @grandSonClick="handler"/>
  5. ...
  6. <script>
  7. import Son from './Son.vue'
  8. export default {
  9. components: { Son },
  10. name: 'GrandFather',
  11. methods:{
  12. handler(arg){
  13. console.log(arg) //arg
  14. }
  15. }
  16. }
  17. </script>

三、$bus事件总线

适用于层级复杂,兄弟组件之间的通信

项目入口文件:main.js

  1. ...
  2. new Vue({
  3. render: h => h(App),
  4. beforeCreate(){
  5. Vue.prototype.$bus=this //在beforeCreate时,vue原型链上添加$bus,$bus等于vue实例,可以使用vue实例的所有方法,包括$emit与on
  6. }
  7. }).$mount('#app')
  8. /*---另一种写法---*/
  9. Vue.prototype.$bus = new Vue()
  10. new Vue({
  11. render: h => h(App),
  12. }).$mount('#app')

组件1:one.vue

  1. ...
  2. <h2>组件1</h2>
  3. <!-- 监听点击,在methods中处理 -->
  4. <button @click="oneClick">子组件按钮</button>
  5. ...
  6. <script>
  7. export default {
  8. ...
  9. methods: {
  10. oneClick() {
  11. this.$bus.$emit('userClick','arg')
  12. },
  13. }
  14. </script>

组件2:two.vue

  1. ...
  2. // 挂载的时候,监听$bus的事件,参数1:事件名,参数2:回调函数
  3. mounted(){
  4. this.$bus.$on("userClick",(arg)=>{
  5. console.log(arg) //arg
  6. })
  7. }