前端页面上通过在线脚本编辑器写前端脚本,然后执行这个脚本,第一次处理这种问题,最后通过构造函数new Function解决
new Function可以传入参数,最后一个参数一定要是函数体,先通过params1,params2占位,调用函数时传入具体参数
var fun = new Function('params1,params2', this.textJs)
fun('小明', '3岁')
下面附上代码,写了个简单示例,示例中通过文本框输入脚本,然后执行
如果需要在脚本执行完之后做一些操作,而脚本中如果有接口请求等异步操作时,可以通过返回一个Promise函数来处理,这里通过定时器来模拟异步操作
<template>
<div style="padding:50px;width:500px">
<a-textarea
v-model="textJs"
placeholder="请输入脚本"
>
</a-textarea>
<a-button @click="test">点击执行</a-button>
<a-button @click="test1">点击执行(异步)</a-button>
<div style="margin: 20px">
执行结果:{{result}}
</div>
</div>
</template>
<script>
export default {
name: 'index',
components: {},
data () {
return {
textJs: '',
result: ''
}
},
methods: {
test () {
var fun = new Function('params1,params2', this.textJs)
this.result = fun('小明', '3岁')
},
test1 () {
var fun = new Function('params1,params2', this.textJs)
fun('小明', '3岁').then(res => {
this.result = res
})
}
}
}
</script>