Use $ on (eventName) monitor events
using $ emit (eventName) trigger events
Api in explanation:
vm.$emit( event, […args] )
parameter:
Event String} {
[args ...]
trigger event on the current instance. Additional parameters are passed to the listener callback.
vm.$on( event, callback )
parameter:
{String | Array} event (2.2.0+ supported only in the array) {Function} callback
usage:
Custom event listeners on the current instance. Events can. $ Emit triggered by vm. The callback function will receive all incoming events triggered additional function parameters.
<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: ' click event dispatch ' , msg2 : ' Click event dispatch 2 ' , } }, Created () { the this . $ ON ([ ' wash_Goods ' , ' drive_Car ' ], (Arg) => { the console.log ( ' true eventful ' ) }) the this . ON $ ( ' wash_Goods ' , (Arg) => { the console.log (Arg) }) the this . $ ON ( ' drive_Car ' , (... Arg) => { the console.log (the BMW, Ferrari) }) }, methods : { emit () { this.$emit('wash_Goods','fish') }, emitOther () { this.$emit('drive_Car',['BMW','Ferrari']) } } } </script>
Parent component sub-assemblies to communication
< Hello @pfn = "parentFn" > </ Hello > < Script > Vue.component ( ' Hello ' , { Template: ' <= Button @ the Click "Fn"> button </ Button> ' , Methods: { // child components: $ EMIT by calling Fn () { the this $ EMIT (. ' PFN ' , ' which is the data transmitted to the parent sub-assembly component ' ) } } }) new new Vue ({ Methods:{ // parent components: providing method parentFn (data) { console.log (log('Parent element: ' , Data) } } }) </ Script >
Non-parent-child communication components
Bus new new Vue = var ()
// in the component B binding custom event
bus. $ ON ( 'ID-Selected', function (ID) {
// ...
})
// event trigger assembly A
bus. $ emit ( 'id-selected' , 1)