$emit

emit:发射,射…的意思吧
用法:
$emit( eventName, […args] )

  • eventName:这是一个事件名,会绑定一个方法。当组件触发事件后,将调用这个方法。
  • …args:附加参数,会被抛出,由上述绑定的方法接收使用。

文档说:它是一个触发当前实例上的事件。附加参数都会传给监听器回调。

示例1:只配合一个事件名使用$emit('welcome'),无附加参数

// 定义组件
Vue.component('welcome-button', {
  template: `
    <button v-on:click="$emit('welcome')">  	// 【1】 $emit只使用了一个事件名welcome,无参数
      Click me to be welcomed
    </button>
  `
})
//使用组件
<div id="emit-example-simple">
  <welcome-button v-on:welcome="sayHi"></welcome-button> 	// 【2】 为事件名welcome绑定一个方法sayHi
</div>

//创建Vue实例
new Vue({
  el: '#emit-example-simple',
  methods: {
    sayHi: function () {	// 【3】 当组件触发事件后,执行welcome所绑定的方法sayHi
      alert('Hi!')
    }
  }
})

示例2:配合额外的参数使用

// 定义组件
Vue.component('magic-eight-ball', {
  data: function () {
    return {
      possibleAdvice: ['Yes', 'No', 'Maybe']
    }
  },
  methods: {
    giveAdvice: function () {
      var randomAdviceIndex = Math.floor(Math.random() * this.possibleAdvice.length)
      //【1】在组件绑定的方法giveAdvice中触发$emit事件,并抛出参数
      this.$emit('give-advice', this.possibleAdvice[randomAdviceIndex])  
    }
  },
  template: `
    <button v-on:click="giveAdvice">
      Click me for advice
    </button>
  `
})

// 使用组件
<div id="emit-example-argument">
  <magic-eight-ball v-on:give-advice="showAdvice"></magic-eight-ball> //【2】为$emit事件绑定一个方法showAdvice
</div>

// 创建Vue实例
new Vue({
  el: '#emit-example-argument',
  methods: {
    showAdvice: function (advice) {    // 【3】方法的参数 advice 用来接收 $emit 抛出的参数
      alert(advice)
    }
  }
})
Logo

前往低代码交流专区

更多推荐