vm.$emit(eventName, [...args])
- 参数:
- {string} eventName
- [...args]
第一种情况:
Vue.component('welcome-button', {
template: `
<button v-on:click="$emit('welcome')">
Click me to be welcomed
</button>
`
})
<div id="emit-example-simple">
<welcome-button v-on:welcome="sayHi"></welcome-button>
</div>
new Vue({
el: '#emit-example-simple',
methods: {
sayHi: function () {
alert('Hi!')
}
}
})
第二种情况:(配合额外的参数)
Vue.component('magic-eight-ball', {
data: function () {
return {
possibleAdvice: ['Yes', 'No', 'Maybe']
}
},
methods: {
giveAdvice: function () {
var randomAdviceIndex = Math.floor(Math.random() * this.possibleAdvice.length)
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>
</div>
new Vue({
el: '#emit-example-argument',
methods: {
showAdvice: function (advice) {
alert(advice)
}
}
})
第三种方法:(在methods使用$event接收)
<div id="app">
<my-component @click="myEvent('click', $event)"></component>
</div>
<script>
Vue.component('my-component', {
template: `
<button v-on:click="$emit('click', '123')">我是按钮</button>
`
})
const vm = new Vue({
el: '#app',
methods: {
myEvent(eventName, event) {
console.log(eventName, event);
}
}
})
</script>