当前位置: 首页 > Web前端 > HTML5

双向数据绑定

时间:2023-04-05 21:58:32 HTML5

数据双向绑定页面渲染服务端渲染浏览器端渲染浏览器端渲染提高开发效率降低维护成本,前后端协同模式;back-end提供界面前端视图和交互逻辑。通过Ajax请求数据,拼接html字符串或使用js模板引擎,Vue等数据驱动框架进行页面渲染。在ES6、Vue等框架出现之前,前端的数据绑定方式:html字符串和js模板引擎的动态拼接。作用:分离数据和视图。模板对应于视图,关注的是如何展示数据,模板外准备的数据,关注的是哪些数据可以展示。工作原理两步:模板解析/编译(Parse/Compile)数据渲染(Render)主流前端模板的三种方式:String-basedtemplating(string-basedparseandcompileprocess)regularexpression-basedtemplateengineregularization匹配{{}}的内容并将其替换为模型es6模板字符串中的数据consttemplate=data=>`

name:${data.name}

age:${data.profile.age

    ${data.skills.map(skill=>`
  • ${skill}
  • `).join('')}
`constdata={name:'zhaomenghuan',profile:{age:24},skills:['html5','javascript','android']}document.body.innerHTML=template(data)Dom-basedtemplating(linkbasedonDom或编译过程)遍历dom树,提取属性和dom内容,将数据写入dom树functionMVVM(opt){this.dom=document.querySelector(opt.el);this.data=opt.data||{};this.renderDom(this.dom);}MVVM.prototype={init:{sTag:'{{',eTag:'}}'},render:function(node){varself=this;varsTag=self.init.sTag;vareTag=self.in它.eTag;varmatches=node.textContent.split(sTag);如果(匹配。长度){varret='';对于(vari=0;i