美文网首页
$emit用法(Vue2)

$emit用法(Vue2)

作者: QYCD | 来源:发表于2023-05-11 10:42 被阅读0次

Vue官网
仅仅是个人学习的记录

子组件可以使用$emit调用父组件中的方法并传递数据

  1. 子组件中定义响应事件: 比如这里的sendMsgToParent('hello world'),这里带了参数'hello world'
  2. 子组件中sendMsgToParent方法通过$emit发射了一个名为fromChildMsg的事件
  3. 父组件实现子组件中$emit定义的fromChildMsg方法,且触发了一个新的方法,这里为showChildMsg
  4. 父组件实现showChildMsg

子组件:

<template>
  <div class="child">
    <van-button
      type="primary"
      @click="sendMsgToParent('hello world')">点击将'hello world'发射给父组件
    </van-button>
  </div>
</template>

<script>
export default {
  name: "ChildModule",
  methods: {
    sendMsgToParent(value) {
      this.$emit('fromChildMsg', value);
    },
  }
}
</script>

<style scoped lang="less">
.child {
  display: flex;
  justify-content: center;
  margin: 16px;
  padding: 16px;
}
</style>

父组件:

<template>
  <div>
    <child-module @fromChildMsg="showChildMsg"></child-module>
  </div>
</template>

<script>
import ChildModule from "../../components/child-module";

export default {
  name: "CurtisTest",
  components: {
    ChildModule
  },
  data() {
    return {

    }
  },
  methods: {
    showChildMsg(data) {
      this.$toast({message: data})
      console.log('>>>show child msg:', data)
    },
  }
}
</script>

<style scoped>

</style>
image.png

相关文章