Vue 事件的基本使用

监听事件(v-on):可以用 v-on 指令监听 DOM 事件,并在触发时运行一些 JavaScript 代码


<button v-on:click="showInfo">点我提示信息</button>

监测到单击事件后执行 methods 中的 showInfo 方法

methods: {
	showInfo(event) {
		alert('你好')
		}
}

简写:

<!-- 普通写法 -->
<button v-on:click="showInfo">点我提示信息</button>
<!-- 简写 -->
<button @click="showInfo">点我提示信息</button>

(不传参)实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue中的事件处理</title>
    <script type="text/javascript" src="js/vue.js"></script>
</head>
<body>

<div id="root">
    <h2>姓名:{{name}}</h2>
    <button v-on:click="showInfo">点我提示信息</button>
</div>

<script type="text/javascript">
    new Vue({
        el: '#root',
        data() {
            return {
                name: '张三',
            }
        },
        methods: {
            showInfo(event) {
                alert('你好')
            }
        }
    })
</script>

</body>
</html>

运行结果



(传参)实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue中的事件处理</title>
    <script type="text/javascript" src="js/vue.js"></script>
</head>
<body>

<div id="root">
    <h2>姓名:{{name}}</h2>
    <button v-on:click="showInfo">点我提示信息(不传参)</button>
    <button v-on:click="showAge($event,16)">点我显示年龄(传参)</button>
</div>

<script type="text/javascript">
    new Vue({
        el: '#root',
        data() {
            return {
                name: '张三',
            }
        },
        methods: {
            showInfo(event) {
                alert('你好')
            },
            showAge(event, age) {
                alert(age)
            }
        }
    })
</script>

</body>
</html>

@click = "deme"@click = "deme($event)" 效果一般,但后者可以传参

写在 methods 中的方法不会进行 数据代理



posted @ 2022-04-03 20:12  春暖花开鸟  阅读(66)  评论(0编辑  收藏  举报