vue项目中碰到需要在模板字符串中动态渲染数组中的每一项,发现v-for不能正常渲染,于是使用原生的js语法来完成 。

let tempul=`
    <ul>
	    ${this.mapInfoshowList.map(item=>{
		    let tempid = `${item.id}`
		    return `<li>
                    <i class="el-icon-star-on"></i>
                    &nbsp;${item.name}:&nbsp;${ele[item.id]}
                </li>`
	    }).join('')}
    </ul>`
let content1 = `
    <div class="mymapinfo">
		${tempul}
		<p><i class="el-icon-location"></i>&nbsp;位置:&nbsp;`+ele.weizhi+`</p>
		<div style="border-top:1px dashed #919191;padding-top:8px;
                    color:rgb(64, 158, 255);font-size:12px;width:98%">
			<span onclick='guijihuifang()'>轨迹回放</span>&nbsp;&nbsp;
			<span >车辆追踪</span>&nbsp;&nbsp;
			<span >实时视频</span>&nbsp;&nbsp;
			<span >历史视频</span>&nbsp;&nbsp;
			<span onclick='cymingling()'>常用命令</span>&nbsp;&nbsp;
			<span >查看街景</span>&nbsp;&nbsp;
		</div>
	</div>`
<script>
    const list = [
        {id:1,name:"aaaa"},
        {id:2,name:"bbbb"},
        {id:3,name:"cccc"},
        {id:4,name:"dddd"}
    ]
    let doc = document.getElementById("box");
    // let htmlcontent = `
    //     <ul v-for="${(item,index) in list}" :key="${index}">
    //         <li id="${item.id}">${item.name}</li>
    //     </ul>
    // `
    
    //v-for不能正常渲染,报错如下
    //template.html:26 Uncaught ReferenceError: item is not defined at template.html:26:23
    
    let teplhtml = `<ul>
        ${list.map(item=>{
                return `<li id="${item.id}">${item.name}</li>`
            }).join('')
        }
    </ul>`

    doc.innerHTML = teplhtml

</script>

效果:

Logo

前往低代码交流专区

更多推荐