Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue emit 传参

作者:冫LOVE灬丶棒棒   发布日期:2025-04-04   浏览:121

// 父组件 (ParentComponent.vue)
<template>
  <div>
    <child-component @custom-event="handleCustomEvent"></child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  methods: {
    handleCustomEvent(data) {
      console.log('Received data from child component:', data);
    }
  }
};
</script>

// 子组件 (ChildComponent.vue)
<template>
  <div>
    <button @click="sendDataToParent">Send Data to Parent</button>
  </div>
</template>

<script>
export default {
  methods: {
    sendDataToParent() {
      const data = { message: 'Hello from child component!' };
      this.$emit('custom-event', data);
    }
  }
};
</script>

解释说明

  1. 父组件

    • 在父组件中,我们引入并注册了子组件 ChildComponent
    • 使用 @custom-event 监听来自子组件的自定义事件 custom-event
    • 当事件触发时,调用 handleCustomEvent 方法,并将子组件传递的数据作为参数接收。
  2. 子组件

    • 在子组件中,定义了一个按钮,点击按钮时会调用 sendDataToParent 方法。
    • sendDataToParent 方法中,通过 this.$emit('custom-event', data) 触发自定义事件 custom-event,并将数据传递给父组件。

通过这种方式,子组件可以向父组件传递数据。

上一篇:vue获取当前时间戳

下一篇:vue 安装axios

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站