一、事件处理
1. 绑定监听:
v-on:xxx="fun"
@xxx="fun"
@xxx="fun(参数)"
默认事件形参: event
隐含属性对象: $event
<button @click='btn3(123,$event)'>按钮3</button>
//方法:
btn3(msg,event){
console.log(msg ,event.target.innerHTML);//按钮3
}
默认事件对象是event,当事件所对应的响应函数执行时,如果已经传值,那么这个时候的就不能对event进行操作。所以就需要用到隐含事件对象$event
,这样就可以既传值又可以拿取event。
<button @click='btn3(123)'>按钮3</button>
//方法:
btn3(event){
console.log(msg ,event.target.innerHTML);//会报错
}
2. 事件修饰符:
.prevent : 阻止事件的默认行为 event.preventDefault()
.stop : 停止事件冒泡 event.stopPropagation()
当前没有用事件修饰符,运行会出现事件冒泡:
<div style="height: 200px;width: 200px;background-color: red;" @click='btn5'>
<div style="height: 100px;width: 100px;background-color: yellow;" @click='btn6'> </div>
</div>
btn5(){
alert("我是红色的大div")
},
btn6(){
alert("我是黄色的小div")
}
event.cancelBubble=true;
这是原来的方法阻止事件冒泡
VUE组织冒泡的方法:@click.stop='btn6'
事件的默认行为:
点击了就会跳转百度
<a href="http://www.baidu.com" @click="btn7">百度一下</a>
阻止默认行为,点击后不会跳转百度了
<a href="http://www.baidu.com" @click.prevent="btn7">百度一下</a>
3. 按键修饰符
.keycode : 操作的是某个keycode值的健
.enter : 操作的是enter键
keyup事件按下指定的键后就被触发
<input type="text" @keyup.enter='btn8'>
//也可以写编码数
<input type="text" @keyup.13='btn8'>
btn8(){
alert(event.target.value);//显示被按下的值
}
二、表单输入绑定
1. 使用v-model(双向数据绑定)自动收集数据
text/textarea
checkbox
radio
select
<body>
<div id="demo">
<form action="/XXX" @submit.prevent='submitForm'>
<span>用户名: </span>
<input type="text" v-model="username" ><br>
<span>密码: </span>
<input type="password" v-model="password"><br>
<span>性别: </span>
<input type="radio" id="female" value="女" v-model="sex" >
<label for="female">女</label>
<input type="radio" id="male" value="男" v-model="sex">
<label for="male">男</label><br>
<!--value里的值和data对应-->
<span>爱好: </span>
<input type="checkbox" id="basket" value="basket" v-model="likes">
<label for="basket">篮球</label>
<input type="checkbox" id="foot" value="foot" v-model="likes">
<label for="foot">足球</label>
<input type="checkbox" id="pingpang" value="pingpang" v-model="likes">
<label for="pingpang">乒乓</label><br>
<span>城市: </span>
<select v-model="cityId">
<option value="">未选择</option>
<option :value='city.id' v-for="(city,index) in allCitys" :key="index">
{{city.name}}
</option>
</select><br>
<span>介绍: </span>
<textarea rows="10" v-model="info"></textarea><br><br>
<input type="submit" value="注册">
</form>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script>
const vm=new new Vue({
el:'#demo',
data:{
username:'',
password:'',
sex:'女',
likes:[],
cityId:'1',
allCitys:[{id:1,name:'北京'},{id:2,name:'上海'},{id:3,name:'武汉'}],
info:''
},
methods:{
submitForm(){
username=this.username;
password=this.password;
sex=this.sex;
likes=this.likes;
allCitys=this.allCitys;
info=this.info;
console.log(username + password +sex +likes +allCitys +info);
}
}
})
</script>
</body>