Vue.js Render関数のサンプルコード

Vue.js Render関数のサンプルコード

vue-cliを利用してプロジェクトを作成すると、main.jsに render: h=> h(App)と記述されており、 こちらのrenderの挙動を確認したかったので、確認用のサンプルコードを掲載。

環境

  • OS windows10 pro
  • エディタ VScode

render: h => h(App)について

render: h => h(App) は、下記のコードの略のようです。

render: function(createElement){
  return createElement(App)
}

サンプルコード

render関数を利用したサンプルコードです。 下記のソースコードをindex.htmlとして作成してブラウザで確認します。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body class="style1">

<div id="app">
</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var app = new Vue({
  render: function(createElement){
    return createElement('h3','Hello World')
  }
}).$mount('#app')
</script>
<style>
.style1 {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 120px;
}

h3 {
margin: 40px 0 0;
color: #41B883;
}
</style>
</body>
</html>

保存したファイルをブラウザで開いて確認。

var app = new Vue({
  render: function(createElement){
    return createElement('h3','Hello World')
  }
}).$mount('#app')

により、<h3>ダグが生成されて Hello World と表示されます

なので、main.js内の下記のコードはrender関数によりApp(App.vue)が id app( <div id=”app”></div> )にマウントされているという意味になります。

import App from './App.vue'

new Vue({
  render: h => h(App),
}).$mount('#app')