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

你好,我是Vam的金豆之路,可以叫我豆哥。2019年年度博客之星、技术领域博客专家。主要领域:前端开发。我的微信是 maomin9761,有什么疑问可以加我哦,自己创建了一个微信技术交流群,可以加我邀请你一起交流学习。最后自己也创建了一个微信公众号,里面的文章是我自己精挑细选的文章,主要介绍各种IT新技术。欢迎关注哦,微信搜索:臻美IT,等你来。


欢迎阅读本博文,本博文主要讲述【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/[email protected]/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'
                },
                on:{
                    click:()=>{
                        alert(1)
                    }
                }
            }, this.text)])
        ])
    }
	})
</script>
</html>

谢谢阅读,如果觉得有感触,麻烦帮忙点个赞,关个注吧!

发布了183 篇原创文章 · 获赞 805 · 访问量 195万+

猜你喜欢

转载自blog.csdn.net/qq_39045645/article/details/105032221
今日推荐