Vue自定義事件:觸發自定義事件


 

一 項目結構

 

 

二 子組件(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>

 

三 父組件(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>

 

四 運行效果

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM