vue中$emit的用法


引自:https://www.cnblogs.com/sweeneys/p/10201458.html

一.事件

關於什么是JavaScript事件可以參考:https://www.w3schools.com/js/js_events.asp

二.$emit

vue中對$emit的定義見:

vm.$emit( eventName, […args] )

  • 參數:

    • {string} eventName
    • [...args]

    觸發當前實例上的事件。附加參數都會傳給監聽器回調。

三.用途與示例

1.父組件可以使用 props 把數據傳給子組件。

1.子組件可以使用 $emit 觸發父組件的自定義事件。

子組件:

復制代碼
<template>
  <div id="translate-form">
      <form>
          <input type="text" v-model="textToTranslate" placeholder="輸入需要翻譯的內容">
          <select>
              <option value="en">English</option>
          </select>
          <input type="submit"  value="翻譯"  v-on:click="formSubmit">
    </form>
  </div>
</template>

<script>
export default {
  name: 'TranslateForm',
  data:function(){
      return{
          textToTranslate:'',
      }
  },
  methods: {
      formSubmit: function(e){
          this.$emit('formSubmit', this.textToTranslate); //父組件監聽的名字必須是formSubmit
          e.preventDefault();
      }
  }
}
</script>

<style>

</style>
復制代碼

 

父組件:

復制代碼
<template>
  <div id="app">
      <h1>在線翻譯</h1>
    <h5>簡單 / 易用 / 便捷</h5>
   <TranslateForm v-on:formSubmit='translateText'></TranslateForm>
  </div>
</template>

<script>
import TranslateForm from './components/TranslateForm'

export default {
  name: 'App',
  components:{
      TranslateForm
  },
  methods:{
      translateText:function(text){
          alert(text)
      }
  }
}
</script>

<style>
#app {
    text-align: center;
}
</style>
復制代碼

當點擊子組件的翻譯的時候,會將輸入的內容彈框:

 


免責聲明!

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



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