VueDay08事件绑定
Vue中的事件绑定:
1.可以使用表达式完成事件操作
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
<h1>点击次数:{{count}}</h1>
<!-- 可以使用表达式完成事件操作 -->
<button @click="count+=1" type="button">点击</button>
<!-- 获取事件对象 -->
<button @click="clickEvent" type="button">点击2</button>
</div>
<script type="text/javascript">
let app = new Vue({
el:"#app",
data:{
count:0
},
methods:{
clickEvent:function(event){
console.log(event)
console.log(this)
this.count++
}
}
})
</script>
</body>
</html>
2.事件传参
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
<ul>
<!-- <li v-for="item,index in stars" :data-id="index">索引值:{{index}}-----内容:{{item}}</li> -->
<li v-for="item,index in stars" @click="clickEvent(index,item,$event)">索引值:{{index}}-----内容:{{item}}</li>
</ul>
</div>
<script type="text/javascript">
let app = new Vue({
el:"#app",
data:{
stars:[
'蔡徐坤','范冰冰','李晨'
]
},
methods:{
clickEvent:function(index,value,event){
console.log(index)
console.log(value)
console.log(event)
}
}
})
</script>
</body>
</html>
3.修饰符
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
<!-- stop修饰符,阻止冒泡事件向上传递 -->
<div class="btnParent" @click="clickParent">
<button @click.stop="clickEvent" type="button">按钮</button>
</div>
<form action="" method="post">
<!-- 绑定输入框回车事件 -->
<input type="text" @keydown.enter.f1="searchWeather" name="username" v-model="city" id="" value="" />
<!-- 阻止默认事件 -->
<input @click.prevent="searchWeather" type="submit" value="提交">
</form>
<div id="weather">
<h1>{{tmp}}</h1>
<h3>{{brief}}</h3>
</div>
<h1>只触发一次修饰符</h1>
<button type="button" @click.once="onceEvent">只触发一次按钮</button>
<!-- @click.ctrl是按住Ctrl或者按住Ctrl加shift都可以触发
如果想要只按住Ctrl需要@click.ctrl.exact-->
<button type="button" @click.ctrl.exact="ctrlEvent">按住Ctrl事件</button>
</div>
<script type="text/javascript">
//配置按键的自定义修饰符
Vue.config.keyCodes.f1 = 112
let app = new Vue({
el:"#app",
data:{
count:0,
city:"广州",
tmp:"",
brief:""
},
methods:{
clickEvent:function(event){
console.log("clickEvent")
},
clickParent:function(){
console.log("clickParent")
},
searchWeather:async function(){
console.log("查询天气")
console.log(this.city)
let httpUrl =`https://free-api.heweather.net/s6/weather/now?location=${this.city}$key=3c497450d8e44c5280421ceaba1db581`
let res = await fetch(httpUrl)
let result = await res.json()
console.log(result)
// let now = result.HeWeather6[0]
},
onceEvent:function(){
console.log("只触发一次")
},
ctrlEvent:function(){
console.log('ctrlEvent')
}
}
})
</script>
</body>
</html>

浙公网安备 33010602011771号