vue3-父子通信

 

 

 

 一个简单的vue3子组件调用父组件方法的demo

<template>  
  <div>  
    <h2>Parent Component父组件</h2>  
    <ChildComponent @notify-parent="handleParentMethod" />  
  </div>  
</template>  
  
<script>  
import { ref } from 'vue';  
import ChildComponent from './Child.vue';  
  
export default {  
  name: 'Parent',  
  components: {  
    ChildComponent  
  },  
  setup() {  
    const handleParentMethod = () => {  
      console.log('Parent method called from child');  
      // 这里可以执行父组件的其他逻辑  
    };  
  
    return {  
      handleParentMethod  
    };  
  }  
};  
</script>
<template>  
  <div>  
    <h3>Child Component子组件</h3>  
    <button @click="notifyParent">Notify Parent</button>  
  </div>  
</template>  
  
<script>  
import { defineComponent, emit } from 'vue';  
  
export default defineComponent({  
  name: 'Child',  
  setup(_, { emit }) {  
    const notifyParent = () => {  
      emit('notify-parent'); // 触发自定义事件  
    };  
  
    return {  
      notifyParent  
    };  
  }  
});  
</script>

 在这个例子中,子组件(Child.vue)有一个按钮,当点击这个按钮时,它会触发一个名为 notify-parent 的自定义事件。父组件(Parent.vue)监听了这个事件,并在事件触发时调用 handleParentMethod 方法。

 

相关推荐

  1. Vue3父子组件通信

    2024-06-18 15:34:02       63 阅读
  2. vue3+ts父子通信

    2024-06-18 15:34:02       35 阅读
  3. Vue父子组件通信代码示例

    2024-06-18 15:34:02       40 阅读
  4. Vue组件通信讲解[父子组件通信]

    2024-06-18 15:34:02       41 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-18 15:34:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-18 15:34:02       101 阅读
  3. 在Django里面运行非项目文件

    2024-06-18 15:34:02       82 阅读
  4. Python语言-面向对象

    2024-06-18 15:34:02       91 阅读

热门阅读

  1. 使用爬虫爬取豆瓣电影Top250(方法一)

    2024-06-18 15:34:02       83 阅读
  2. Protobuf详解及入门指南

    2024-06-18 15:34:02       34 阅读
  3. Android的布局有哪些?

    2024-06-18 15:34:02       35 阅读
  4. MySQL触发器基本结构

    2024-06-18 15:34:02       28 阅读
  5. 大文件上传实现

    2024-06-18 15:34:02       28 阅读
  6. 前端BUG记录-a-spin和a-pagination

    2024-06-18 15:34:02       33 阅读
  7. 探索 HNSW:分层导航小世界算法的深度解析

    2024-06-18 15:34:02       33 阅读
  8. 正则表达式 - 在线工具

    2024-06-18 15:34:02       31 阅读
  9. 从史上最惨618看经济趋势

    2024-06-18 15:34:02       27 阅读
  10. 【HarmonyOS NEXT】鸿蒙customScan (自定义界面扫码)

    2024-06-18 15:34:02       30 阅读