父组件代码
<template>
  <div>
    <!-- 原生DOM事件 -->
    <button @click="handle">点击</button>
    <!-- 原本是自定义事件,加上native修饰符转换成原生DOM事件,实际上是在Event1组件的根元素上加click事件 -->
    <Event1 @click.native="handle1"></Event1>
    <Event2 ref="event2" @getName="handle2" :getNum="getNum"></Event2>
  </div>
</template>
<script>
import Event1 from "./components/Event1";
import Event2 from "./components/Event2";
export default {
  name: "App",
  data() {
    return {};
  },
  methods: {
    handle() {
      console.log(123);
    },
    handle1() {
      console.log("Event1组件");
    },
    getNum(num) {
      console.log("收到子组件Event2传过来的数字:" + num);
    },
    //与自定义事件绑定
    handle2(name) {
      console.log("收到子组件Event2传过来的名字:" + name);
    },
  },
  components: {
    Event1,
    Event2,
  },
  // 组件挂载时
  mounted() {
    // 绑定自定义事件
    this.$refs.event2.$on("getName", this.handle2);
  },
};
</script>
子组件代码
<template>
  <div class="box">
    <button @click="sendName">点击发送名字</button>
    <button @click="sendNum">点击发送数字</button>
  </div>
</template>

<script>
export default {
  name: "Event2",
  data() {
    return {
      uname: "joke",
      num: "123456",
    };
  },
  props: ["getNum"],
  methods: {
    sendName() {
      this.$emit("getName", this.uname);
    },
    sendNum() {
      this.getNum(this.num);
    },
  },
};
</script>

输出情况:点击发送名字 控制台输出如下: 打印了两遍

 解决办法:1、直接在绑定事件的时候,直接在回调中写相应的执行语句,在上面子组件中就不用写 @getName="handle2",然后handle2方法也不用写了

mounted() {
    // 绑定自定义事件
    this.$refs.event2.$on("getName", function (name) {
      console.log("收到子组件Event2传过来的名字:" + name);
    });
  },

2、使用props直接将自定义事件传给子组件,子组件直接调用并传参,参考上面getNum方法

最后,之前想在原有代码上解决打印两遍问题,但没啥思路,网上也没搜到解决方法,有哪个高手知道答案的,评论区见!

Logo

前往低代码交流专区

更多推荐