使用 $on(eventName) 監聽事件
使用 $emit(eventName) 觸發事件
Api 中的解釋:
vm.$emit( event, […args] )
參數:
{string} event
[…args]
觸發當前實例上的事件。附加參數都會傳給監聽器回調。
vm.$on( event, callback )
參數:
{string | Array} event (數組只在 2.2.0+ 中支持) {Function} callback
用法:
監聽當前實例上的自定義事件。事件可以由 vm.$emit 觸發。回調函數會接收所有傳入事件觸發函數的額外參數。
<template> <div> <p @click='emit'>{{msg}}</p> </div> </template> <script> export default { name: 'demo', data () { return { msg : '點擊后派發事件' } }, created () { this.$on('wash_Goods',(arg)=> { console.log(arg) }) }, methods : { emit () { this.$emit('wash_Goods',['fish',true,{name:'vue',verison:'2.4'}]) } } } </script>
<template> <div> <p @click='emit'>{{msg}}</p> <p @click='emitOther'>{{msg2}}</p> </div> </template> <script> export default { name: 'demo', data () { return { msg : '點擊后派發事件', msg2 : '點擊后派發事件2', } }, created () { this.$on(['wash_Goods','drive_Car'],(arg)=> { console.log('真多事') }) this.$on('wash_Goods',(arg)=> { console.log(arg) }) this.$on('drive_Car',(...arg)=> { console.log(BMW,Ferrari) }) }, methods : { emit () { this.$emit('wash_Goods','fish') }, emitOther () { this.$emit('drive_Car',['BMW','Ferrari']) } } } </script>
子組件到父組件通訊
<hello @pfn="parentFn"></hello> <script> Vue.component('hello', { template: '<button @click="fn">按鈕</button>', methods: { // 子組件:通過$emit調用 fn() { this.$emit('pfn', '這是子組件傳遞給父組件的數據') } } }) new Vue({ methods: { // 父組件:提供方法 parentFn(data) { console.log('父組件:', data) } } }) </script>
非父子組件通訊
var bus = new Vue()
// 在組件 B 綁定自定義事件
bus.$on('id-selected', function (id) {
// ...
})
// 觸發組件 A 中的事件
bus.$emit('id-selected', 1)