An alternative to the eval() function in js

Because eval() has security issues, it is generally not used, so write a method to make a replacement for it

Operations in strings will not be executed in templates. One way is to use eval(), but there will be security issues

, use the following method instead

<template>
<span>{
    
    {handleEval(txt)}}<span>
</template>
<script>
data() {
  return {
    txt: '50*50'
  }
}
methods: {
  handleEval(fn) {
    const Fn = Function; // 一个变量指向Function,防止有些前端编译工具报错
    return new Fn('return ' + fn)();
  }
}
</script>

Guess you like

Origin blog.csdn.net/weixin_42627850/article/details/128932104