首頁  >  文章  >  web前端  >  使用render方法的圖文詳解

使用render方法的圖文詳解

php中世界最好的语言
php中世界最好的语言原創
2018-03-23 11:47:339850瀏覽

這次帶給大家使用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結果如下:

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

百度地圖裡顯示marker與Polyline

怎麼開發微信小程式的獲取用戶手機號功能

以上是使用render方法的圖文詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn