vue之间的传值问题---4通过事件传递数据 this.$emit 子传父

baozhengrui / 2024-10-15 / 原文


// 子组件
<template>
  <div>
    <button @click="handleClick">传递参数</button>
  </div>
</template>

<script>
export default {
  methods: {
    handleClick() {
      this.$emit('event-name', '传递的值');
    },
  },
};
</script>

// 父组件
<template>
  <div>
    <child-component @event-name="handleEvent"></child-component>
  </div>
</template>

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

export default {
  components: {
    ChildComponent,
  },
  methods: {
    handleEvent(value) {
      console.log(value); // 输出:传递的值
    },
  },
};
</script>