Js中执行变量中的命令语句,也就是所谓的宏替换(很实用的例子)
由其做动态编程时非常有用,必须符合js中的语法,用eval能够执行。
var aaa="alert('这是变量中的语句')";
eval(aaa);
1、ES6例子(eval)
let aaa = `
if (m_class == '1' && m_titleId == one_item.titleId)
{ ${uuu}.splice(0,2);alert('111'); }
`
eval(aaa);
2、通用例子(eval)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script type="text/javascript">
var a1 = "张飞";
var a2 = "李白";
alert("改前的a2=" + a2);
var i = 2;
comm = "a" + i + "=" + "'中国人'";
alert(comm);
eval(comm);
alert("改后的a2=" + a2);
</script>
</html>
3、new Function(考虑兼容性、可读性和安全性问题,强烈推荐这个,不推荐eval)
变量
let aaa="look";
let fn = new Function(`console.log('${aaa}')`); //'a'
fn();
传参:
let m_name="终于实现宏替换了!";
let m_com = "return "+`alert('${m_name}')`;
let fn = new Function(m_com);
fn();
4、在Vue2中new Function宏替换的应用示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>js实现变量名的宏替换</title>
</head>
<style>
.mButton {
height: 100px;
width: 200px;
background-color: rgb(48, 111, 228);
margin: 0 auto;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.13/dist/vue.js"></script>
<body>
<div id="arrlist">
<div @click.stop="jsonDelete('y')" class="mButton"></div>
</div>
</body>
<script type="text/javascript">
// 通过Js操作数组和对象最详细实例(图文+完整源代码)
var arrlist = new Vue({
el: "#arrlist",
data: {
y: [{ "id": "888" }, { "id": "666" }],
x: [{ "id": "119" }, { "id": "110" }],
},
methods: {
jsonDelete(ArrayName) {
alert('aaa');
let fn = new Function(`return this.${ArrayName}`).bind(this);
s=fn();
alert(s[0].id);
}
},
})
</script>
</html>
5、在Vue3中new Function宏替换的应用示例
<template>
<div class="m_box" @click="noSeeAll">
<!-- 第一个固定标签 -->
<div @click.stop="jsonDelete('x')" class="mButton"></div>
</div>
</template>
<script>
import { reactive} from "vue";
export default {
name: "LoginPage",
setup() {
let y = reactive([{ "id": "888" }, { "id": "666" }]);
let x =reactive([{ "id": "119" }, { "id": "110" }]) ;
let vm
// =============================【Json删除】
// function jsonDelete() {
function jsonDelete(ArrayName, ClassNumber, KeyName, Id, TwoKeyName, ThreeKeyName) {
alert(ArrayName);
let fn = new Function(`return this.${ArrayName}`).bind(vm);
let s=fn();
alert(s[0].id);
}
vm = {
y,
x,
jsonDelete
}
// ================================ 【return - 变量和方法名】
return vm;
},
};
</script>
<style scoped>
.mButton {
height: 100px;
width: 200px;
background-color: rgb(48, 111, 228);
margin: 0 auto;
}
</style>
在此,感谢QQ呢称为【鲸】的好友,帮我解决了很多问题。