相信很多学习vue的人有和我一样遇到这样的坑的,也有很多学习很顺利的,这是一个明媚的夏天,阳光下面是可爱的vue宝宝,不废话了,写重点,vue的页面和html一样是遵循古老而神秘的法则的,即页面渲染从上到下。
<!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://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="test">
<blog-post v-for="post in posts" v-bind:key="post.id" v-bind:post="post" ></blog-post>
</div>
</body>
<script>
var test = new Vue({
el:'#test',
data: {
posts:[
{id:1,title:'做梦',content:'是的'},
{id:2,title:'做梦',content:'是的'},
{id:3,title:'做梦',content:'是的'},
]
}
})
Vue.component('blog-post',{
props: ['post'],
template: `
<div class="blog-post">
<h3>{{ post.title }}</h3>
<div v-html="post.content">
</div>
</div>
`,
data(){
return{}
}
})
</script>
</html>
上面的代码看着没什么错误,但是却犯了兵家大忌,那就是把vue实例化当成了排头兵,而把先锋部队组件定义当成了后勤补养的勤务兵,这组件还不得闹翻天,还没见到敌人自己先打起来了,于是页面就加载不出来。正确的写法
<!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://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="test">
<blog-post v-for="post in posts" v-bind:key="post.id" v-bind:post="post" ></blog-post>
</div>
</body>
<script>
Vue.component('blog-post',{
props: ['post'],
template: `
<div class="blog-post">
<h3>{{ post.title }}</h3>
<div v-html="post.content">
</div>
</div>
`,
data(){
return{}
}
})
var test = new Vue({
el:'#test',
data: {
posts:[
{id:1,title:'做梦',content:'是的'},
{id:2,title:'做梦',content:'是的'},
{id:3,title:'做梦',content:'是的'},
]
}
})
</script>
</html>