Vue click事件传递参数的示例教程
IT利刃出鞘 人气:0简介
说明
本文用示例介绍Vue中事件传参的方法。
Vue的事件用法为:v-on:click="xxx"。可以用@click="xxx"来简写。
本处采用click这个事件进行展示,其他的事件也是一样的。
官网
只传自定义参数
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>this is title</title> </head> <body> <div id="app"> <button @click="clickHere('hello')">点我</button> </div> <script src="js/vue.js"></script> <script>Vue.config.productionTip = false</script> <script> let vm = new Vue({ el: '#app', methods: { clickHere: function (param1) { console.log("参数:"); console.log(param1); } } }) </script> </body> </html>
结果
只传事件参数
不指定参数时,默认会传递事件。当然也可以通过$event来传递事件。
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>this is title</title> </head> <body> <div id="app"> <button @click="clickHere">点我</button> <!--等价于下边这个--> <!--<button @click="clickHere($event)">点我</button>--> </div> <script src="js/vue.js"></script> <script>Vue.config.productionTip = false</script> <script> let vm = new Vue({ el: '#app', methods: { clickHere: function (e) { console.log("事件:"); console.log(e); } } }) </script> </body> </html>
结果
传事件和自定义参数
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>this is title</title> </head> <body> <div id="app"> <button @click="clickHere($event, 'hello')">点我</button> </div> <script src="js/vue.js"></script> <script>Vue.config.productionTip = false</script> <script> let vm = new Vue({ el: '#app', methods: { clickHere: function (event, param1) { console.log("事件:"); console.log(event); console.log("参数:"); console.log(param1); } } }) </script> </body> </html>
结果
动态参数(从局部取值)
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>this is title</title> </head> <body> <div id="app"> <div v-for="hero in heros"> <button @click="clickHere(hero.name)">点我</button> </div> </div> <script src="js/vue.js"></script> <script>Vue.config.productionTip = false</script> <script> let vm = new Vue({ el: '#app', methods: { clickHere: function (param1) { console.log("参数:"); console.log(param1); } }, data: { heros: [{ name: "Iron Man", age: 30 }, { name: "Captain America", age: 40 }] } }) </script> </body> </html>
结果
动态参数(从全局数据取值)
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>this is title</title> </head> <body> <div id="app"> <button @click="clickHere({message})">点我</button> </div> <script src="js/vue.js"></script> <script>Vue.config.productionTip = false</script> <script> let vm = new Vue({ el: '#app', methods: { clickHere: function (param1) { console.log("参数:"); console.log(param1); } }, data: { message: "hello world" } }) </script> </body> </html>
结果
其他网址
加载全部内容