vue中的方法与事件

Vue 2019-10-04 766

方法定义在methods中,一般调用时与大部分编程语言一样,都需要写括号。
事件的种类有很多,vue定义事件标准采用v-on,比如点击事件v-on:click="handleClick()"
举一个综合的例子:

<body>  
    <div id="app">  
        点击次数: {{count}}  
        <button type="button" @click="count++">点击</button>  
        点击次数2: {{counter}}  
        <button type="button" @click="handleClick">点击</button>  
        <br>  
        <a href="https://www.baidu.com" @click="handleClick2('禁止打开', $event)">打开链接</a>  
    </div>  
</body>  
<script>  
    var app = new Vue({  
        el: '#app',  
        data: {  
            message: 'Hello Vue',  
            count: 0,  
            counter:0,  
        },  
        methods:{  
            handleClick: function () {  
                this.counter ++;  
            },  
            handleClick2: function (message1, event) {  
                event.preventDefault();//preventDefault() 方法阻止元素发生默认的行为(例如,当点击提交按钮时阻止对表单的提交)  
                window.alert(message1);  
            }  
        }  
    })  
</script>  
</html>  

@click调用的方法名后可以不跟()。此时,如果该方法有参数,默认将原生事件对象event传入。
参照上方的a标签,Vue提供了一个特殊的变量$event,用于访问原生DOM事件。

标签:Vue

文章评论

评论列表

已有0条评论