练习2 :将该示例的 render 写法改写为 template 写法,加以对比,总结出两者的差异性,深刻理解其使用场景。
解答:template写法简洁,直观,更容易理解,render复杂,当需要对dom元素深入操作时,是更好的选择,可以做到更深层次的操作。
1. vinput.vue render函数与template写法对比:
template:
<template> <div> <span>昵称</span> <input :value="value" @input="handleInput"> </div> </template>
render:
render(h){ var _this =this; return h('div',[ h('span','昵称: '), h('input',{ attrs:{ type:'text' }, domProps:{ value:this.vlaue }, on:{ input(event){ //_this.value = event.target.vlaue; _this.$emit('input',event.target.value); } } }) ]); }
2. vtextarea.vue
template:
<template> <div> <span>留言内容</span> <textarea :value="value" @input="handleInput" ref="message"></textarea> </div> </template>
render:
render(h){ var _this=this; return h('div',[ h('span','留言内容'), h('textarea',{ attrs:{ placeholder:'请输入留言内容' }, domProps:{ value:this.value }, ref:'message', on:{ input(event){ //_this.value=event.target.value; _this.$emit('input',event.target.value); } } }) ]); },
list.vue
template:
<template> <div v-if="list.length" class="list"> <div v-for="(msg, index) in list" :key="index" class="list-item"> <span>{{msg.name +': '}} </span> <div class="list-msg"> <p>{{msg.message}}</p> <a class="list-reply" @click="handleReply(index)">回复</a> <a class="list-del" @click="handleDel(index)">删除</a> </div> </div> </div> <div v-else class="list-nothing"> 留言内容为空 </div> </template>
render
render(h){ var _this = this; var list=[]; this.list.forEach((msg, index)=>{ var node = h('div',{ attrs:{ class:'list-item' } },[ h('span',msg.name + ': '), h('div',{ attrs:{ class:'list-msg' } },[ h('p',msg.message), h('a',{ attrs:{ class:'list-reply' }, on:{ click(){ _this.handleReply(index); } } },'回复'), h('a',{ attrs:{ class:'list-del' }, on:{ click(){ _this.handleDel(index); } } },'删除') ]) ]) list.push(node); }); if(this.list.length){ return h('div',{ attrs:{ class:'list' }, },list); }else{ return h('div',{ attrs:{ class:'list-nothing' } },'留言内容为空'); } },