Vue筆記之render函式(一):render: h => h(App)

夢裡夢一發表於2018-10-14

前言

render函式很難啃下來,我看的頭暈眼花.今天可是我生日啊,搞什麼鬼!

在建立vue專案之後,main.js檔案中主模板檔案的配置會有兩種方式:

//第一種方式:
import Vue from 'vue'
import App from './App.vue'
new Vue({
  //此處的el對應的是index.html中的div標籤的id
  el: '#app',
  components: { App },
  // 此處template應該是被內部拿去使用了,沒有看到顯示的app標籤
  template: '<App/>'
});
複製程式碼
//第二種方式:
import Vue from 'vue'
import App from './App.vue'
new Vue({
  el: '#app',
  render: h => h(App)
  //render函式以js的方式(虛擬節點)去渲染元件
  //App是元件,是專案的主元件
})
複製程式碼

學到了render函式去解釋一下第二種方式:

render: h => h(App)
//es6語法箭頭函式的簡寫形式
//h又是createElement的另一種寫法,這是vue規定的,沒有為什麼
複製程式碼

相當於:

render: (h) => {
    return h(App)
}
複製程式碼

相當於:

//箭頭函式轉為普通函式
render: function(h) {
    return h(App)
}
複製程式碼

相當於:

render: function(createElement) {
    return createElement(App)
}
複製程式碼

簡單演示:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="https://unpkg.com/vue"></script>
</head>
<body>
  <div id="app">
  <!--無需顯示的去用MyComponent元件標籤,在此處也可顯示-->
  </div>

  <script>
    let MyComponent = {
      template: `
        <div>子元件</div>
      `
    }
    let vm = new Vue({
      el: '#app',
      render: h => h(MyComponent) 
    })
  </script>
</body>
</html>
複製程式碼

相關文章