在 `left-card.vue` 组件中,通过点击事件触发 `$bus` 实例的 `emit` 方法来传递值给 `right-card.vue` 组件。

<template>
  <div>
    <button @click="passValue">Pass Value to Right Card</button>
  </div>
</template>

<script>
  export default {
    methods: {
      passValue() {
        // 传递的值
        const value = 'Hello from Left Card';

        // 通过 $bus 实例的 emit 方法触发事件,并传递值
        this.$bus.$emit('leftToRightValue', value);
      }
    }
  };
</script>

然后,在 `right-card.vue` 组件中,监听 `$bus` 实例的 `on` 方法,以接收从 `left-card.vue` 组件传递过来的值。

<template>
  <div>
    <p>Received Value: {{ receivedValue }}</p>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        receivedValue: ''
      };
    },
    mounted() {
      // 监听 leftToRightValue 事件,并获取传递的值
      this.$bus.$on('leftToRightValue', (value) => {
        this.receivedValue = value;
      });
    }
  };
</script>

这样,当在 `left-card.vue` 组件中点击按钮时,会触发 `passValue` 方法,并通过 `$bus` 实例的 `emit` 方法将值传递给 `right-card.vue` 组件,在 `right-card.vue` 组件中通过监听 `$bus` 实例的 `on` 方法来接收并显示传递的值。

Vue.js 组件间通信:使用 $bus 传递值

原文地址: https://www.cveoy.top/t/topic/b59h 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录