Vue学习

给组件绑定原生事件

2018-08-03  本文已影响0人  椰果粒

如果就是想给子组件添加原生的事件,就用@click.native=""

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>给组件绑定原生事件</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <counter @click.native="handleClick"></counter>
    </div>
    <script>
        var counter = {
            template : '<div>{{content}}</div>',
            data : function(){
                return {
                    content : "hello world"
                }
            }
        }
        var vm = new Vue({
            el : "#app",
            components : {
                counter : counter
            },
            methods : {
                handleClick : function(){
                    alert('click');
                }
            }
        })
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>给组件绑定原生事件</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <!-- 这里绑定的不是原生的click,而是自定义的,是从子组件传递过来的 -->
        <counter @click="handleClick"></counter>
    </div>
    <script>
        var counter = {
            template : '<div @click="handleChildClick">{{content}}</div>',
            data : function(){
                return {
                    content : "hello world"
                }
            },
            methods : {
                handleChildClick : function(){
                    alert("child click");
                    // 将子组件点击事件传递给父组件
                    this.$emit("click");
                }
            }
        }
        var vm = new Vue({
            el : "#app",
            components : {
                counter : counter
            },
            methods : {
                handleClick : function(){
                    alert('click');
                }
            }
            
        })
    </script>
</body>
</html>
上一篇下一篇

猜你喜欢

热点阅读