给组件绑定原生事件

给组件绑定原生事件

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="./vue.js"></script>
    <!-- <script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script> -->
</head>
<body>
<div id="root">
    //这里绑定的事件是指的自定义事件
    <child @click="handleClick"></child>
</div>
<script type="text/javascript">
    Vue.component("child", {
        //这里绑定的事件是指的原生的事件
        template: "<div @click='handleChildClick'>I am a child</div>",
        methods: {
            handleChildClick: function() {
                alert("childClick");
                //想触发父组件的handleClick必须这样做:
                this.$emit("click")
            }
        }
    });
    var vm = new Vue({
        el: "#root",
        methods: {
            handleClick: function() {
                //此处不能触发<child @click="handleClick"></child>绑定的handleClick事件,因为这是自定义事件
                alert("fatherClick");
            }
        }
    })
</script>
</body>
</html>

但是,像上面这种写法太麻烦,有时候就想在child(原生组件)监听,可以加上.native:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="./vue.js"></script>
    <!-- <script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script> -->
</head>
<body>
<div id="root">
    //加了.native可以触发handleClick <br>
    <child @click.native="handleClick"></child>
    //不加.native无法触发handleClick <br>
    <child @click="handleClick"></child>

</div>
<script type="text/javascript">
    Vue.component("child", {
        //这里绑定的事件是指的原生的事件
        template: "<div>I am a child</div>",
    });
    var vm = new Vue({
        el: "#root",
        methods: {
            handleClick: function() {
                //此处不能触发<child @click="handleClick"></child>绑定的handleClick事件,因为这是自定义事件
                alert("fatherClick");
            }
        }
    })
</script>
</body>
</html>