js 代码字符串动态生成方法

171 阅读1分钟

创建javascript方法

/**
 * 创建一个函数,该函数可以执行JavaScript代码
 * @param code 代码字符串
 * @param args 变量名,该方法对应参数名
 * @returns {handle}
 * 使用 makeJavascriptFunction(`console.log(a,b)`, ['a','b'])?.handle('123','345')
 */
const makeJavascriptFunction = (code: string, args: string[]) => {
  try {
    const handle = new Function(...args, code)
    return { handle }
  } catch (err: any) {
    ElMessage({
      message: err.message || '',
      title: '脚本语法错误',
      type: 'warning'
    })
  }
}

使用创建的方法

字符串内变量应与传参的名称一致 resp options

let arr = [{ a: 123, b: 123 }]
let options = { a: 123, b: 123 }

makeJavascriptFunction(`console.log(resp,options); return resp;`, ['resp', 'options'])?.handle(arr, options)