1.普通事件 @click,@input,@change,@xxx等事件,经过this.$emit('xxx',...)触发
写法案例:
<div id="example-3">
<button v-on:click="say('hi')">Say hi</button>
<button v-on:click="say('what')">Say what</button>
</div>
new Vue({
el: '#example-3',
methods: {
say: function (message) {
alert(message)
}
}
})
2.修饰符事件 @input.trim,@click.stop,@submit.prevent等,通常用于原生HTML元素,自定义组件须要自行开发支持
写法案例:
<!-- 阻止单击事件冒泡传播 -->
<a v-on:click.stop="doThis"></a>
<!-- 提交事件不再重载页面 -->
<form v-on:submit.prevent="onSubmit"></form>
<!-- 修饰符可以串联 -->
<a v-on:click.stop.prevent="doThat"></a>
<!-- 只有修饰符 -->
<form v-on:submit.prevent></form>
<!--表单修饰符-->
1).lazy
在默认情况下, v-model 在每次 input 事件触发后将输入框的值与数据进行同步 。你可以添加 lazy 修饰符,从而转变为使用 change事件进行同步。适用于输入完所有内容后,光标离开才更新视图的场景。
2).trim
如果要自动过滤用户输入的首尾空白字符,可以给 v-model 添加 trim 修饰符:
<input v-model.trim="msg">
这个修饰符可以过滤掉输入完密码不小心多敲了一下空格的场景。需要注意的是,它只能过滤首尾的空格!首尾,中间的是不会过滤的。
3).number
如果想自动将用户的输入值转为数值类型,可以给 v-model 添加 number 修饰符:
<input v-model.number="value" type="text" />
案例
子组件事件
<template>
<div>
name:{{name}}
<input :value="name" @change="handChange"/>
<div @click="divClick">
<button @click="handClick">重置成功</button>
<button @click.stop="handClick">重置成功</button>
</div>
</div>
</template>
<script>
export default {
name:"Event",
props:{
name:String
},
methods:{
divClick(){
this.$emit("change","");
},
handChange(e){
//触发父组件的change事件
this.$emit("change",e.target.value);
},
handClick(){
}
}
}
</script>
<style scoped>
</style>
在父组件中应用事件
<template>
<div id="app">
{{msg}}
<Event
@change="onChangeVal"
:name="name"
/>
</div>
</template>
<script>
import Event from './components/Event'
export default {
name: 'App',
data() {
return {
msg: "hello 入门小站",
name:"name",
type:"入门",
list:['入门','小站'],
view:true
}
},
methods: {
onChangeVal(val){
this.name=val;
}
},
components: {
Event //必须先声明
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>