Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can Vue render function process single file component?

I use Vue cli and implement simple-webpack template.

In the entry file main.js, there's a code like below:

render: h => h(App)

I know that h is an alias of createElement function, I wonder why a single file component like App can be passed in as an argument, official vue document didn't mention this.

Does anyone know why is it?

like image 589
Arel Lin Avatar asked Mar 27 '18 09:03

Arel Lin


1 Answers

Single file component (SFC) in vue js has a .vue extension.

In webpack we use a loader called vue-loader which tests for .vue files

{
    test: /\.vue$/,
    loader: 'vue-loader',
    options: {
      loaders: {
      }
      // other vue-loader options go here
    }
}

these SFCs are converted into a plain es6 modules .

The <template> part is transformed into render functions by vue-template-complier and injected into the exported module.

The <style> tag is similarly processed by any preprocessors for sass or less and then by Post-css to scope the CSS accordingly and dynamically added inside the the <head> as <style> tag with the help of vue-style-loader.

For example if the App.vue file looks as follows:

<template>
    <div>
        <p class="myClass">{{msg}}</p>
    </div>
</template>

<script>
    export default{
        data(){
            return{
                msg: "Vue is awesome!"
            }
        }
    }
</script>

It is converted to a plain module where exported as an object shown below:

export default {
    data(){
        return{
            msg: "Vue is awesome!"
        }
    },
    render(createElement) {
        return createElement("div", 
            [createElement("p", {class: {'myClass': true}}), this.msg]
        )
    }
}

This is imported as import App from './path/to/App.vue and used in root vue instance as

 new Vue({
     el:"#app",
     render: h => h(App)
 })

You can check out this fiddle where App is passed as a plain object to render function of root vue instance.

For more detailed info you can checkout this video where Evan You explains it more elaborately.

like image 120
Vamsi Krishna Avatar answered Oct 17 '22 11:10

Vamsi Krishna