赞
踩
模板引擎的一个有点:它是将数据转为视图的最优雅的方法
对于下面的数据
- [
- {"name":"小名",'age':"12","sex":'男'},
- {"name":"小红",'age':"12","sex":'女'},
- {"name":"小王",'age':"12","sex":'男'},
- ]
相信vue的玩家首先想到的是
- <ul>
- <template v-for="item in data">
- <li class="hd">{{ item.name }}的信息</li>
- <li class="bd">
- <p>姓名{{ item.name }</p>
- <p>年龄{{ item.name }}</p>
- <p>性别{{ item.name }}</p>
- </li>
- </template>
-
- </ul>
而还没学vue的朋友,就只能进行dom操作了
像纯DOM
- <!DOCTYPE html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
-
- <body>
- <ul>
-
- </ul>
- <script>
- let arr = [
- { "name": "小名", 'age': "12", "sex": '男' },
- { "name": "小红", 'age': "12", "sex": '女' },
- { "name": "小王", 'age': "12", "sex": '男' },
- ]
- let ul = document.querySelector('ul')
- for (const item of arr) {
- let li = document.createElement('li')
- let div1 = document.createElement('div')
- div1.className = 'hd'
- let div2 = document.createElement('div')
- div2.className = 'bd'
- div1.innerHTML = item.name + '的基本信息'
- let p1 = document.createElement('p')
- let p2 = document.createElement('p')
- let p3 = document.createElement('p')
- p1.innerHTML = '姓名:' + item.name
- p2.innerHTML = '年龄:' + item.age
- p3.innerHTML = '性别:' + item.sex
- div2.appendChild(p1)
- div2.appendChild(p2)
- div2.appendChild(p3)
- li.appendChild(div1)
- li.appendChild(div2)
- ul.appendChild(li)
- }
- </script>
- </body>
-
- </html>
通过数组的join方法
- <!DOCTYPE html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
-
- <body>
- <ul>
-
- </ul>
- <script>
- let data = [
- { "name": "小名", 'age': "12", "sex": '男' },
- { "name": "小红", 'age': "12", "sex": '女' },
- { "name": "小王", 'age': "12", "sex": '男' },
- ]
- let ul = document.querySelector('ul')
- for (const item of data) {
- let arr = [
- '<li>',
- ' <div class="hd">'+item.name+'的信息</div>',
- ' <div class="bd">',
- ' <p>姓名:'+item.name+'</p>',
- ' <p>年龄:'+item.age+'</p>',
- ' <p>性别:'+item.sex+'</p>',
- ' </div>',
- '</li>',
- ]
- let htmlStr = arr.join('')
- ul.innerHTML += htmlStr
- }
-
- </script>
- </body>
-
- </html>
以及es6推出的模板字符串
- <!DOCTYPE html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
-
- <body>
- <ul>
-
- </ul>
- <script>
- let ul = document.querySelector('ul')
- let data = [
- { "name": "小名", 'age': "12", "sex": '男' },
- { "name": "小红", 'age': "12", "sex": '女' },
- { "name": "小王", 'age': "12", "sex": '男' },
- ]
- for (const item of data) {
- ul.innerHTML += `
- <li>
- <div class="hd">${item.name}的信息</div>
- <div class="bd">
- <p>姓名:${item.name}</p>
- <p>年龄:${item.age}</p>
- <p>性别:${item.sex}</p>
- </div>
- </li>
- `
- }
- </script>
- </body>
-
- </html>
此为实现的效果
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。