vue learning [bind native events to components]

Posted by Transwarp-Tim on Thu, 21 Nov 2019 15:52:53 +0100

When a click event is defined in the parent component, and the click event is defined in the methods of the parent component, clicking on the page will have no response. So what should we do?
We can define a click event (native event) on the dom in the template of the subcomponent, and define the click event in the methods of the subcomponent. However, when we click the page, it will only alert(child click).
Why is that? The click event of the parent component is regarded as a user-defined event by vue, which is not detected after clicking. In this case, the child component needs to trigger the click 'user defined' event to the parent component, that is, this.$emit('change '). Then, finish. First responded to child click, then to click.

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Verification of component parameters</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
    <child @change="handleClick"></child>    <!--The parent component here is equivalent to a custom event-->
</div>
</body>
</html>
<script>
    Vue.component('Child', {
        template: '<div @click="handleChildClick">child</div>',      /* Native event */
        methods:{
            handleChildClick:function () {
                alert("child click")
                this.$emit('change') // Pass custom events to parent
            }
        }
    })
    var vm = new Vue({
        el: '#app',
        methods:{
            handleClick:function () {
                alert("click");
            }
        }
    })
</script>

But it's so troublesome!! What shall I do?
We can directly add native after @ click defined by the parent component to tell vue that the event defined by me is a native event!! It's all
like this:

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Verification of component parameters</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
    <child @click.native="handleClick"></child>    <!--Declared here, native event-->
</div>
</body>
</html>
<script>
    Vue.component('Child', {
        template: '<div>child</div>'
    })
    var vm = new Vue({
        el: '#app',
        methods:{
            handleClick:function () {
                alert("click");
            }
        }
    })
</script>

Topics: Vue npm