前端工作小结65-自定义事件

1子组件

mongo.vue

<template>
    <button @click="eat">按钮</button>
</template>
 
<script>
export default {
  created() {
    this.$on("eat", function(fruit) {
      console.log("子组件接收自己发射的事件");
    });
  },
  methods: {
    eat() {
      console.log("子组件发射事件");
      this.$emit("eat", "芒果");
    }
  }
};
</script>
<style>
</style>

2父组件

app.vue

<template>
  <div id="app">
    <h3>{{name}}</h3>
    <!-- 子组件 -->
    <mongo @eat='eat'/>
  </div>
</template>
 
<script>
import Mongo from "./components/Mongo";
 
export default {
  name: "app",
  data() {
    return {
      name: ""
    };
  },
  methods: {
    eat(fruit) {
      console.log("父组件接收事件");
      this.name = fruit;
    }
  },
  components: { Mongo }
};
</script>
 
<style>
</style>

posted @ 2022-09-02 21:48  前端导师歌谣  阅读(31)  评论(0)    收藏  举报