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>
源码:https://github.com/mifunc/rum…
发表回复