在 html 或 jsp 页面中我们总能碰到监听 DOM 事件来触发 javaScript 代码,下面我们就简单聊聊 vue.js 中的监听事件是怎么处理的。
在 vue.js 中监听事件是通过 v-on 指令来实现的,先看一下简单的监听事件代码。
- <!DOCTYPE html>
- <html>
- <head lang="en">
- <meta charset="UTF-8">
- <title>
- </title>
- <script type="text/javascript" src="vue.js">
- </script>
- </head>
- <body>
- <div id="app">
- <button v-on:click="count += 1">
- 点击测试
- </button>
- <p>
- 这个按钮被点击了{{count}}次
- </p>
- </div>
- </body>
- <script>
- var vm = new Vue({
- el: "#app",
- data: {
- count: 0
- }
- })
- </script>
- </html>
下面再看看监听方法事件的代码示例
- <!DOCTYPE html>
- <html>
- <head lang="en">
- <meta charset="UTF-8">
- <title>
- </title>
- <script type="text/javascript" src="vue.js">
- </script>
- </head>
- <body>
- <div id="app">
- <button v-on:click="test">
- 点击测试
- </button>
- </div>
- </body>
- <script>
- var vm = new Vue({
- el: "#app",
- data: {
- name: 'Vue.js'
- },
- // 在 `methods` 对象中定义方法
- methods: {
- test: function(event) {
- // `this` 在方法里指当前 Vue 实例
- alert('Hello ' + this.name + '!')
- // `event` 是原生 DOM 事件
- alert(event.target.tagName)
- }
- }
- })
- </script>
- </html>
内联处理器方法,内联 javaScript 语句
- <!DOCTYPE html>
- <html>
- <head lang="en">
- <meta charset="UTF-8">
- <title>
- </title>
- <script type="text/javascript" src="vue.js">
- </script>
- </head>
- <body>
- <div id="app">
- <button v-on:click="say('say hello')">
- say hello
- </button>
- <button v-on:click="say('say goodbye')">
- say goodbye
- </button>
- </div>
- </body>
- <script>
- var vm = new Vue({
- el: "#app",
- data: {
- name: 'Vue.js'
- },
- // 在 `methods` 对象中定义方法
- methods: {
- say: function(message) {
- alert(message)
- }
- }
- })
- </script>
- </html>
来源: http://www.jb51.net/article/113927.htm