SoFunction
Updated on 2025-04-07

How to dynamically bind different events to components

vue dynamically binds different events to components

Scene

Dynamic binding based on user-configured events. That is, users can dynamically select click, change, blur and other events

Need to dynamically bind @click, @change or @bulr according to the user's configuration event

The actual operation code is as follows:

<template>
  <div>
    <el-input v-for="(item,index) in list"
        :key="index"
        v-on:[]=""></el-input>
  </div>
</template>
<script>
export default {
    name: "eventPage",
    data() {
        return {
            list: [{ event: "change" ,eventName:"changeName"}]
            }
        },
    methods: {
        changeName(){
            ('change event')
        }
    }
};
</script>

The above dynamic events. Can be abbreviated

<el-input @[]=""></el-input>

vue component binding event is invalid

Bind events directly on components in vue are invalid, for example, the following code is invalid:

    &lt;div &gt;
        &lt;btn @click='alert(1)'&gt;Click&lt;/btn&gt;
    &lt;/div&gt;
    &lt;script src="/ajax/libs/vue/2.6.11/"&gt;&lt;/script&gt;
    &lt;script&gt;
        ('btn', {
            template:`
            &lt;button&gt;
                &lt;slot&gt;&lt;/slot&gt;
            &lt;/button&gt;
            `
        })
        new Vue({
            el: '#app', 
            data() {
                return {
                }
            }
        });
    &lt;/script&gt;

It can also be achieved if you must bind events directly on the component.

The following provides two methods, and one of them can be selected.

1. You may have many times you want to listen for a native event directly on the root element of a component. At this point, you can use the .native modifier of v-on

&lt;div &gt;
        &lt;btn @='alert(1)'&gt;Click&lt;/btn&gt;
&lt;/div&gt;

2. It comes from within

    &lt;div &gt;
        &lt;btn @click='alert(1)'&gt;Click&lt;/btn&gt;
    &lt;/div&gt;
    &lt;script src="/ajax/libs/vue/2.6.11/"&gt;&lt;/script&gt;
    &lt;script&gt;
        ('btn', {
            template:`
            &lt;button @click='handleClick'&gt;
                &lt;slot&gt;&lt;/slot&gt;
            &lt;/button&gt;
            `,
            methods: {
                handleClick(e){
                    this.$emit('click','e')
                }
            },
        })
        new Vue({
            el: '#app', 
            data() {
                return {
                }
            }
        });
    &lt;/script&gt;

The above is personal experience. I hope you can give you a reference and I hope you can support me more.