#Vue 字符串转Function
方法一: eval
/* 定义字符串类型方法 */
const func="(value)=>{console.log(value);return value}"
/* 字符串转Function */
str_to_func(func,value){
return eval(func)(value)
}
/* 使用 */
str_to_func(func,1)
结果是控制台输出1
有些代码检查会报错,但是不影响使用
ESLint: eval can be harmful. (no-eval)
方法二: new Function
/* 定义字符串类型方法 */
const func = 'console.log(value);return value'
/* 字符串转Function */
str_to_func (func, value) {
const Fn = new Function('value', func)
return Fn(value)
}
/* 使用 */
str_to_func(func,1)
/* 也可以直接使用 */
const func = 'console.log(value);return value'
const Fn = new Function('value', func)
Fn(1)
结果也是控制台输出1
但是代码检查依旧会有问题
ESLint: The Function constructor is eval. (no-new-func)