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

  • 参数

    • {string} eventName
    • […args]触发当前实例上的事件。附加参数都会传给监听器回调。
  • 示例:

只配合一个事件名使用 $emit

  1. Vue.component('welcome-button', {
  2. template: `
  3. <button v-on:click="$emit('welcome')">
  4. Click me to be welcomed
  5. </button>
  6. `
  7. })
  1. <div id="emit-example-simple">
  2. <welcome-button v-on:welcome="sayHi"></welcome-button>
  3. </div>
  1. new Vue({
  2. el: '#emit-example-simple',
  3. methods: {
  4. sayHi: function () {
  5. alert('Hi!')
  6. }
  7. }
  8. })

配合额外的参数使用 $emit

  1. Vue.component('magic-eight-ball', {
  2. data: function () {
  3. return {
  4. possibleAdvice: ['Yes', 'No', 'Maybe']
  5. }
  6. },
  7. methods: {
  8. giveAdvice: function () {
  9. var randomAdviceIndex = Math.floor(Math.random() * this.possibleAdvice.length)
  10. this.$emit('give-advice', this.possibleAdvice[randomAdviceIndex])
  11. }
  12. },
  13. template: `
  14. <button v-on:click="giveAdvice">
  15. Click me for advice
  16. </button>
  17. `
  18. })
  1. <div id="emit-example-argument">
  2. <magic-eight-ball v-on:give-advice="showAdvice"></magic-eight-ball>
  3. </div>
  1. new Vue({
  2. el: '#emit-example-argument',
  3. methods: {
  4. showAdvice: function (advice) {
  5. alert(advice)
  6. }
  7. }
  8. })