vue3中监听,组件通信如父子传值、Vuex、Event Bus的使用

目录

一、监听

二、父子传值:

1、父传子:

2、子传父

三、全局状态管理(Vuex):

四、事件总线(Event Bus):


一、监听

<template>
  <div>
    <p>Count: {
   
   { count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';

const count = ref(0);

const increment = () => {
  count.value++;
};

// 使用 watch 监听 count 的变化
watch(count, (newValue, oldValue) => {
  console.log(`count changed from ${oldValue} to ${newValue}`);
});
</script>

二、父子传值:

1、父传子:

我们有一个父组件ParentComponent和一个子组件ChildComponent。在父组件中,我们使用:childProp="parentData"将数据传递给子组件。在子组件中,我们使用defineProps来接收父组件传递的属性(props)。

ParentComponent.vue:

<template>
  <div>
    <p>我是父组件</p>
    <ChildComponent :childProp="parentData" />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

const parentData = ref('Hello from parent');
</script>

ChildComponent.vue:

<template>
  <div>
    <p>子组件接收的数据: {
   
   { childProp }}</p>
  </div>
</template>

<script setup>
import { defineProps } from 'vue';

const props = defineProps({
  childProp: String
});
</script>

2、子传父

在父组件中,我们使用 @childEvent="handleChildEvent" 来监听子组件的 childEvent 事件,并在 handleChildEvent 方法中接收子组件传递的数据。这样,当在子组件点击按钮时,子组件会通过自定义事件将数据传递给父组件,父组件监听事件并接收数据。

ChildComponent.vue:

<template>
  <button @click="sendDataToParent">向父组件传递数据</button>
</template>

<script setup>
import { defineEmits } from 'vue';

const emits = defineEmits(['childEvent']);

const sendDataToParent = () => {
  emits('childEvent', 'Hello from child');
};
</script>

在子组件中,我们使用 defineEmits 来定义一个自定义事件 childEvent,然后通过 sendDataToParent 方法触发该事件,并传递数据 'Hello from child'

ParentComponent.vue:

<template>
  <div>
    <p>来自子组件的数据: {
   
   { dataFromChild }}</p>
    <ChildComponent @childEvent="handleChildEvent" />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

const dataFromChild = ref('');

const handleChildEvent = (data) => {
  dataFromChild.value = data;
};
</script>

三、全局状态管理(Vuex):

Vuex 是 Vue 官方提供的状态管理库,用于管理应用的共享状态。通过 Vuex,你可以在任何组件中访问和修改全局状态,实现组件之间的数据共享。

以下是一些简单的步骤,以示例代码为基础,展示如何设置和使用Vuex。

  1. 安装 Vuex:首先,确保在你的项目中安装了Vuex:
    cnpm install vuex
  2. 创建 Vuex Store:在你的应用中创建一个Vuex store,用于管理全局状态。在一个名为 store.js 的文件中编写以下代码:
    import { createStore } from 'vuex';
    
    const store = createStore({
      state() {
        return {
          count: 0
        };
      },
      mutations: {
        mutationsIncrement(state, newCount) {
          state.count = newCount;
        }
      },
      actions: {
        increment(context, count) {
          context.commit('mutationsIncrement', count);
        }
      },
      getters: {
        getCount(state) {
          return state.count;
        }
      }
    });
    
    export default store;
    
  3.  在主应用中使用 Vuex Store:在主应用中引入并使用创建好的 Vuex store:
    在 main.js 中:
    import { createApp } from 'vue';
    import App from './App.vue';
    import store from './store';
    
    const app = createApp(App);
    app.use(store);
    app.mount('#app');
    
  4. 在组件中使用 Vuex:在你的组件中使用 Vuex 中的状态、mutations、actions 和 getters。 
    在组件中使用状态:
    <template>
      <div>
        <p>Count: {
         
         { count }}</p>
        <button @click="increment">Increment</button>
      </div>
    </template>
    
    <script setup>
    import { useStore } from 'vuex';
    
    const store = useStore();
    const count = ref('')
    
    const increment = () => {
      // 修改 count
      store.commit('increment', 'This is new');
      // 获取 count
      count.value = store.state.count
    };
    </script>
    

这只是一个简单的示例,展示了如何设置和使用 Vuex。在实际应用中,你可以在 store 中管理更多的状态、mutations、actions 和 getters,以满足你的项目需求。如果你需要更多关于 Vuex 的详细信息,建议查阅 Vuex 的官方文档。 

四、事件总线(Event Bus)

事件总线是一种在组件之间传递事件和数据的模式,它可以用于简单的通信场景。你可以通过创建一个 Vue 实例来作为事件总线,然后在需要的组件中使用该实例来监听和触发事件。

在 Vue 3 中并没有 on 和 emit 方法,用于自定义事件的监听和触发对于全局事件总线的需求,Vue 3 推荐使用第三方库如 mitt 。

以下是创建和使用事件总线的简单示例:

安装 mitt 库

cnpm install mitt

EventBus.js:

创建一个 mitt 实例来作为事件总线,然后在组件中引入该实例进行事件监听和触发。

import mitt from 'mitt';

const eventBus = mitt();

export default eventBus;

ComponentA.vue:

在一个组件中,你可以使用事件总线实例来触发事件。

<template>
  <div>
    <button @click="sendMessage">发送消息到组件B</button>
  </div>
</template>

<script setup>
import eventBus from './EventBus';

const sendMessage = () => {
  eventBus.emit('message', 'Hello from Component A');
};
</script>

ComponentB.vue:

在另一个组件中,你可以使用事件总线实例来监听来自其他组件的事件。

<template>
  <div>
    
  </div>
</template>

<script setup>
import eventBus from './EventBus';
import { ref, onMounted } from 'vue';

const receivedMessage = ref('');

onMounted(() => {
  eventBus.on('message', (message) => {
    receivedMessage.value = message;
    console.log('接收到的消息:', receivedMessage.value)
  });
});
</script>

在这个示例中,我们创建了一个事件总线实例 eventBus,并在 ComponentA 组件中使用 eventBus.emit 来触发 message 事件,然后在 ComponentB 组件中使用 eventBus.on 来监听 message 事件,并在事件被触发时更新接收到的消息。

请注意,事件总线模式适用于简单的通信场景,但随着应用变得更加复杂,可能会导致事件的管理和维护变得困难。对于更复杂的通信需求,你可能会考虑使用其他通信方式,如 Vuex 或其他状态管理工具。

猜你喜欢

转载自blog.csdn.net/weixin_44523517/article/details/132168662