温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

给组件绑定原生事件

发布时间:2020-07-02 02:45:27 来源:网络 阅读:198 作者:梁十八 栏目:web开发
<!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>
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI