事件我们并不陌生,以前我们都是用的框架帮我们配置好的事件,我们称为原生事件。通过v-on:或者@绑定事件,事件触发时执行对应的程序。
今天我们自己来创建一个事件,我们要先知道事件的三要素:事件源 target 、事件类型type 、监听器handler
在自定义事件中,事件源就是我们设置的组件,事件类型我们自己命名,监听器就是事件绑定的那个函数,我们想要完成一个组件的完成,我们需要在组件中用到vm对象原型上的一个方法:this.$emit("事件类型名","要给触发的事件的函数handler传入值(可省)")
我们来试一下:
创建box1.vue组件并设置一个事件:事件名为myevent,事件触发条件为msg=5时才触发。
- <div class="box1">
- <p>{{msg}}p>
- <button v-on:click="add">点击加1button>
- div>
- <script>
- export default{
- data() {
- return {
- msg:1
- }
- },
- methods: {
- add(){
- this.msg++
- if (this.msg==5) {
- this.$emit("myevent",1,"参数2")
- }
- }
- },
- }
- script>
- <style>
- .box1{
- width: 100px;
- height: 100px;
- background-color: aqua;
- }
- style>
在app.vue组件中,导入注册box1组件,并使用其myevent事件:绑定的监听器为fn函数,事件触发时控制台打印信息和我们用arguments接收传入的参数。
- <div class="app">
- <h1>app主键h1>
- <Box1 @myevent="fn">
- Box1>
- div>
-
- <script>
-
- import Box1 from "@/components/box1.vue"
- export default {
- methods: {
- fn(){
- console.log("事件触发了",arguments);
- }
- },
- components:{
- Box1,
- }
- }
- script>
-
- <style>
- .app{
- width: 400px;
- height: 400px;
- background-color: burlywood;
- }
- style>
效果:
二、也可以通过this.$emit()这个方法来实现给组件标签间接绑定原生事件,让子组件的原生事件触发时调用父组件的函数。
代码展示:创建box2.vue组件并当组件内事件触发时创建事件。
- <div class="box2">
- <h3 @click="fn">点我打印h3>
- div>
- <script>
- export default{
- methods: {
- fn(){
- this.$emit("click1")
- }
- },
- }
- script>
- <style>
- .box2{
- width: 200px;
- height: 200px;
- background-color: yellow;
- }
- style>
在app.vue组件中,导入注册box2组件,并为创建的对象提供函数。
- <div class="app">
- <h1>app主键h1>
- <Box2 @click1="fn1">Box2>
- div>
-
- <script>
- import Box2 from "@/components/box2.vue"
- export default {
- methods: {
- fn1(){
- console.log("原生");
- }
- },
- components:{
- Box2
- }
- }
- script>
-
- <style>
- .app{
- width: 400px;
- height: 400px;
- background-color: burlywood;
- }
- style>
三、事件修饰符.native,通过这个可以直接在组件上绑定原生属性。
如:给上面的Box2绑定点击事件
- <div class="app">
- <h1>app主键h1>
- <Box2 @click.active="fn1">Box2>
- div>