vue Design Patterns observer mode (custom events)

vue the observer pattern, is transmitted to the parent sub-assembly for the assembly parameters, i.e. subassembly emit a custom event name, and its parameters, to the parent component by receiving an event, the event is the first parameter custom event name, first two parameters to the callback function

Sub-assembly code

<template>
    <div>
        <input type="text" v-model="inputVal" @change="sendParams">
    </div>
</template>

<script>
export default {
    data () {
        return {
            inputVal: ''
        }
    },
    methods: {
        sendParams () {
            this.$emit('handlerVal',this.inputVal)
        }        
    }
}
</script>

 

Father component code

<template>
    <div>
        <Child @handlerVal="getData"/>
    </div>
</template>
import Child from 'components/Child'
<script>
    export default {
        data () {
            return {
                inputVal: ''
            }
        },
        methods: {
            getData (data) {
               console.log(data)
            }
        }
    }
</script>

 

Very simple, needless to say, the focus here, vue through custom event is how to do this?

Actually very simple, only you need to mount an object on the Vue, then key (key) of the object as a custom event name, value (value) as a parameter to customize event delivery. Once With this idea, the following is a specific implementation of the code is as follows

<script type="text/javascript">
var Event = {
    on: function(eventName,arg) {
        this.handles = this.handles || {};
        this.handles[eventName] = arg || null ;
    },
    emit: function (eventName, cb) {
        if(this.handles[eventName]) {
            cb(this.handles[eventName])
        }
    }
}

Event.on('lcq','haha')
Event.emit('lcq',getData)
function getData(data) {
    console.log(data) // haha
}
</script>

In fact, write Event.handles the object key and value

Guess you like

Origin blog.csdn.net/luchuanqi67/article/details/80987038