Vue render深入开发讲解(2)

//HTML <div> <vv-isshow :show="isShow"><slot>我被你发现啦3!!!</slot></vv-isshow> </div> //js //组件形式 Vue.component('vv-isshow', { props:{ show:{ type: Boolean, default: true } }, render:function(h){ if(this.show ) return h('div',this.$slots.default); }, }); var vm = new Vue({ el: "#app", data: { isShow:true } });

列表渲染

之前是这样写的,而且v-for 时template内必须被一个标签包裹

//HTML <div> <vv-aside v-bind:list="list"></vv-aside> </div> //js //组件形式 Vue.component('vv-aside', { props:['list'], methods:{ handelClick(item){ console.log(item); } }, template:'<div>\ <div v-for="item in list" @click="handelClick(item)" :class="{odd:item.odd}">{{item.txt}}</div>\ </div>', //template:'<div v-for="item in list" @click="handelClick(item)" :class="{odd:item.odd}">{{item.txt}}</div>',错误 }); var vm = new Vue({ el: "#app", data: { list: [{ id: 1, txt: 'javaScript', odd: true }, { id: 2, txt: 'Vue', odd: false }, { id: 3, txt: 'React', odd: true }] } });

render这样写

//HTML <div> <vv-aside v-bind:list="list"></vv-aside> </div> //js //侧边栏 Vue.component('vv-aside', { render: function(h) { var _this = this, ayy = this.list.map((v) => { return h('div', { 'class': { odd: v.odd }, attrs: { title: v.txt }, on: { click: function() { return _this.handelClick(v); } } }, v.txt); }); return h('div', ayy); }, props: { list: { type: Array, default: () => { return this.list || []; } } }, methods: { handelClick: function(item) { console.log(item, "item"); } } }); var vm = new Vue({ el: "#app", data: { list: [{ id: 1, txt: 'javaScript', odd: true }, { id: 2, txt: 'Vue', odd: false }, { id: 3, txt: 'React', odd: true }] } });

v-model

之前的写法

//HTML <div> <vv-models v-model="txt" :txt="txt"></vv-models> </div> //js //input Vue.component('vv-models', { props: ['txt'], template: '<div>\ <p>看官你输入的是:{{txtcout}}</p>\ <input v-model="txtcout" type="text" />\ </div>', computed: { txtcout:{ get(){ return this.txt; }, set(val){ this.$emit('input', val); } } } }); var vm = new Vue({ el: "#app", data: { txt: '', } });

render这样写

//HTML <div> <vv-models v-model="txt" :txt="txt"></vv-models> </div> //js //input Vue.component('vv-models', { props: { txt: { type: String, default: '' } }, render: function(h) { var self=this; return h('div',[h('p','你猜我输入的是啥:'+this.txt),h('input',{ on:{ input(event){ self.$emit('input', event.target.value); } } })] ); }, }); var vm = new Vue({ el: "#app", data: { txt: '', } });

总结

render函数使用的是JavaScript 的完全编程的能力,在性能上是占用绝对的优势,小编只是对它进行剖析。至于实际项目你选择那种方式进行渲染依旧需要根据你的项目以及实际情况而定。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/pxywg.html