#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)