您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

使用render方法的图文详解

2026/2/1 7:12:29发布23次查看
这次给大家带来使用render方法的图文详解,使用render方法的注意事项有哪些,下面就是实战案例,一起来看一下。
先说一下对官网上demo的个人理解:
<!doctype html> <html> <head>   <title>vue的render方法说明</title>   <script src="vue.js"></script> </head> <body> <p id="app">   <child :level="1">     hello world   </child> </p> <script type="text/x-template" id="anchored-heading-template">   <p>     <h1 v-if="level === 1">       <slot></slot>     </h1>     <h2 v-if="level === 2">       <slot></slot>     </h2>     <h3 v-if="level === 3">       <slot></slot>     </h3>     <h4 v-if="level === 4">       <slot></slot>     </h4>     <h5 v-if="level === 5">       <slot></slot>     </h5>     <h6 v-if="level === 6">       <slot></slot>     </h6>   </p> </script> <script type="text/javascript"> vue.component('child', {   template: '#anchored-heading-template',   props: {     level: {       type: number,       required: true     }   } });   new vue({     el: #app   }) </script> </body> </html>
虽然使用template定义组件的方法非常的直观,但是这样会造成代码过长。可以使用render的方法
<!doctype html> <html> <head>   <title>vue的render方法说明</title>   <script src="vue.js"></script> </head> <body> <p id="app">   <child :level="1">     hello world   </child> </p> <script type="text/javascript"> vue.component('child', {   render:function (createelement) {     var body=this.$slots.default;     //this.$slots返回了一个组件分发下来的元素和内容     //this.$slots.default返回了具名的内容     return createelement(       'h'+this.level,       //this.level是利用v-bind注入到组件中的level       body     )   },   //因为vue中组件父组件无法向子组件注入内容。所以我们需要通过   //v-bind定义一个key,value向子组件注入内容。所要接收的值也需要在定义组件时的props属性中的定义一下   props:{     level:{     }   } });   new vue({     el: #app   }) </script> </body> </html>
下面是一个slot具名分发的demo:介绍了createlement的用法:
<!doctype html> <html> <head>   <title>vue的render方法说明</title>   <script src="vue.js"></script> </head> <body> <p id="app">   <child>     <p slot="header">this is header</p>     <p slot="center">this is center</p>     <p slot="footer">this is footer</p>   </child> </p> <script type="text/javascript">   vue.component('child', {     render: function (createelement) {      var header=this.$slots.header;      var center=this.$slots.center;      var footer=this.$slots.footer; //createelement第一个参数是标签名,第二个参数是值      return createelement('p',[        createelement('p', header),        createelement('p', center),        createelement('p', footer),      ])     }   });   new vue({     el: #app   }) </script> </body> </html>
所创建的组件的demo结果如下:
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
百度地图里显示marker与polyline
怎么开发微信小程序的获取用户手机号功能
以上就是使用render方法的图文详解的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product