参数的介绍及传递
我们看一看那个按钮绑定的点击事件
<button @click="fun1()"></button>
<!-- 此处:按钮绑定了函数 fun1(),并且是以点击的方式触发的 -->
<!-- 通常:我们是不传递参数的 -->
如果当我们传递了参数,此参数在 Vue 对象中就会得到相应的处理
<button @click="fun1(3)" id="susu">参数的传递</button>
fun1:function(value1){console.log(value1)}
// Vue 配置项 methods 里面的方法
// 功能:将传递的参数用变量 value1 接收并且在控制台显示出来
在浏览器中打开,可以发现每点击一次按钮,参数会在控制台上面重复输出一次
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="vue.js"></script>
</head>
<body>
<button @click="fun1(3)" id="susu">参数的传递</button>
<script>
new Vue({
el:"#susu",
data:{},
methods:{
fun1:function(value1){
console.log(value1)
}}
})
</script>
</body>
</html>
event 参数的介绍
除了这种我们自己传递的参数之外,还有一个特殊的参数
<button @click="fun1($event)" id="susu" name="susu 的 button">event 参数的介绍</button>
<!-- 此处特别注意一下 按钮的 name -->
fun1:function(event){console.log(event.target.name)
// Vue 配置项 methods 里面的方法
// 功能:特殊参数通过方法 event.target.name 获取了使用此函数标签的 name 值
在浏览器中实现过程,我们每点击一次按钮,标签的 name 值被输出一次
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="vue.js"></script>
</head>
<body>
<button @click="fun1($event)" id="susu" name="susu 的 button">event 参数的介绍</button>
<script>
new Vue({
el:"#susu",
data:{},
methods:{
fun1:function(event){
console.log(event.target.name)
}}
})
</script>
</body>
</html>
event 参数的简单使用(阻止浏览器默认跳转)
此处介绍 event 参数在标签(a)超链接中的使用
<a href="https://www.baidu.com/" @click="fun1($event)">百度一下</a>
fun1:function(event){event.preventDefault(),window.location = "新链接"}
// 通过 event 参数 阻止超链接默认跳转(event.preventDefault())
// 通过 event 参数 跳转新的页面(window.location = "新链接")
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="vue.js"></script>
</head>
<body>
<a href="https://www.baidu.com/" @click="fun1($event)">百度一下</a>
<script>
new Vue({
el:"#susu",
data:{},
methods:{
fun1:function(event){
// 阻止默认跳转
event.preventDefault(),
// 重新跳转到新页面
window.location = "https://cn.vuejs.org/"
}
}
})
</script>
</body>
</html>