Vue是怎么渲染template内的标签内容的?

我们在使用Vue做项目时,都会用到脚手架,相应的我们会在template写标签内容。那么你知道为什么会在template写标签吗?这当中经过了怎样的处理呢?

<template>
  <div id="app">
    <div id="nav">
    </div>
    <router-view/>
  </div>
</template>

<style lang="less">

</style>

其实Vue在处理template时,是经过这样处理的,它是通过内置的render方法处理我们输入的标签,生成VNodes。下面我注释了template内的代码,你可以先看下效果,然后注释掉render方法内的内容,取消注释template。看下前后效果是否一样。

<!DOCTYPE html>
<html>
<head>
    <title>render</title>
</head>
<style type="text/css">
    #text{
        font-weight: bold;
        font-size: 26px;
    }
</style>
<body>
    <div id="app">
       
    </div>
</body>
<script type="text/javascript" src="https://unpkg.com/vue@2.6.11/dist/vue.js"></script>
<script type="text/javascript">
    const vm = new Vue({
        el:'#app',
        data: {
            text: 'hello world',
            style1: {
            width: '200px',
            height: '200px',
            border: '1px solid red'
            },
            style2: {
            textAlign: 'center'
            },
            colorText: {
            color:'blue'
            }
        },
     //    template:`<div :style='style1'>
     //    <p :style='style2'>
     //        <span :style='colorText' @click='cli()' id='text'>{{text}}</span>
     //    </p>
     //    </div>`,
     //    methods:{
        // cli(){
        //     alert(1)
        // }
    //    },
    render(createElement) {
        return createElement('div', {
            style: this.style1
        }, [
            createElement('p', {
                style: this.style2
            }, [createElement('span', {
                style: this.colorText,
                attrs:{
                    id:'text'
                },

更多请见:http://www.mark-to-win.com/tutorial/50767.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值