Home > Net >  Call Vue 3 function by it's name in string variable
Call Vue 3 function by it's name in string variable

Time:11-08

In my script setup SFC I want to dynamically call another function from the same component by it's name in string variable, right now I'm doing it that way:

let functionName = "myFunction(param)";
eval(functionName);

I read on MDN docs that using eval is dangerous, I tried to use return Function but it gives me "Uncaught ReferenceError: myFunction is not defined" or "TypeError: [...] is not a function"

is there a better way or do I have to use eval?

CodePudding user response:

What you have done here is assigned a string to the variable functionName. Though your post lacks some context, if you are just trying to call one function from another, it would look like this:

<script setup>

function myFunction(params){};
function myOtherFunction(){
   myFunction()
};

</script>

Or more like how you have it written. This is valid syntax as well:

let myFunction = (params) => {};
let myOtherFunction = (params) => {
  myFunction(params);
}

CodePudding user response:

Define your function as property inside a literal object then call it using brackets:

const funcs={
  myFunction:function(param){
   ///
  }
}

// and now you could call it like 
funcs["myFunction"](yourArg)

CodePudding user response:

Maybe to explain better what you need, but if you receive function with params like string:

const app = Vue.createApp({
  methods: {
    myFunc(msg) {
      alert(msg)
    }
  },
  mounted() {
    let functionName = "myFunc(param)"
    const func = functionName.slice(0, functionName.indexOf('('))
    const param = functionName.slice(functionName.indexOf('(')   1, functionName.length - 1)
    this[func](param)
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo"></div>

  • Related