Search code examples
javascriptvue.jseval

Using eval() in Vue2 inside a method works and doesn't work at the same time


I have a list of function names inside a component, and depending on certain conditions, different functions must be called from the same place.

I was not able to create a dynamic function in my template, so I created a function 'callMethod(name)' which does an eval. The eval WORKS, i.e. it calls a method in my component which then calls a method in the parent. However, I get a console error enter code hereTypeError: this.myFunctionName(...) is not a function

While everything is working, I don't want these errors puked into my console.

If I comment out the the eval statement, and explicitly type out the method, then it runs as well, but without the error.

if

  callMethod(name) {
        eval('this.' + name + '()');
        //this.clickShowDeleteAcceptForm()
        console.log('did I get here?')
    },

is called with name='clickShowDeleteAcceptForm' then I get it working with the error, as explained. The console output does not happen.

    callMethod(name) {
        //eval('this.' + name + '()');
        this.clickShowDeleteAcceptForm();
        console.log('did I get here?')

    },

if I call this (obviously the 'name' variable is irrelevant) then it works without the error! Console output does happen.

[Vue warn]: Error in v-on handler: "TypeError: this.clickShowDeleteAcceptForm(...) is not a function"

found in

---> <MessagesGuest> at src/components/ManageMessages/Guest.vue
       <ManageMessages> at src/components/ManageMessages/MessagesListing.vue
         <App> at src/App.vue
           <Root>
warn @ vue.runtime.esm.js?2b0e:619
logError @ vue.runtime.esm.js?2b0e:1874
globalHandleError @ vue.runtime.esm.js?2b0e:1869
handleError @ vue.runtime.esm.js?2b0e:1835
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1852
invoker @ vue.runtime.esm.js?2b0e:2169
original._wrapper @ vue.runtime.esm.js?2b0e:6855
vue.runtime.esm.js?2b0e:1878 TypeError: this.clickShowDeleteAcceptForm(...) is not a function
    at eval (eval at callMethod (Guest.vue?cfd3:95), <anonymous>:1:33)
    at VueComponent.callMethod (Guest.vue?cfd3:106)
    at click (eval at ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"6235b99d-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/ManageMessages/Guest.vue?

Solution

  • I don't know what is the problam but using eval is a big No No. Use this insted:

    callMethod(name) {
        this[name]();
        //this.clickShowDeleteAcceptForm()
        console.log('did I get here?')
    },