Search code examples
vue.jscomponentsemit

Can I dynamically change parent's function name in the child component instance with my settings in data?


Beginner looking for help. thank you so much.

Can I dynamically change parent's function name in the child component instance with my settings in data?

it works fine with this: <my-component btntext="TEXT" @emitfn="fn1">

but I need to do this: <my-component btntext="TEXT" @emitfn="emitname"> and Vue gives me error...

here's my code:

<div id="root">
    <my-component btntext="TEXT" @emitfn="emitname"></my-component>
</div>

<script>
Vue.component('myComponent', {
    props: ['btntext'],
    template: '<button @click="childFN">{{btntext}}</button>',
    methods: {
        childFN: function(){
            this.$emit("emitfn");
        }
    },
    data: function(){
        return {
            emitname: 'fn1'
        }
    }
});

var vm = new Vue({
    el: '#root',
    methods: {
        fn1: function(){
            alert('fn1');
        },
        fn2: function(){
            alert('fn2');
        }
    }
});
</script>

Solution

  • You can reach a method using this.$options.methods['methodName'].

    In your case you can use this:

    Parent component:

    <my-component btntext="TEXT" @emitfn="emitfn"></my-component>
    
    
    methods: {
       fn1: function(){
          alert('fn1');
       },
       fn2: function(){
          alert('fn2');
       },
       emitfn(emitname) {
          this.$options.methods[emitname]();
       },
    }
    

    Child component:

    methods: {
       childFN: function(){
          this.$emit("emitfn", this.emitname);
       }
    },