image.png
image.png
image.png
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>組件</title>
</head>
<body>
<div id="root">
<hello></hello>
<hr>
<!-- 第三步:使用組件 -->
<student></student>
<hr/>
<school></school>
<hr/>
</div>
<!-- 第二個(gè)容器 -->
<div id="root2">
<hello></hello>
</div>
<script src="../js/vue.js"></script>
<script>
//第一步:定義組件
const student = Vue.extend({
template:`
<div>
<h2>學(xué)生姓名:{{name}}</h2>
<h2>學(xué)生年齡:{{age}}</h2>
</div>
`,
data(){
return {
name:'丫丫',
age:2
}
}
});
const school =Vue.extend({
template:`
<div>
<h2>學(xué)校名稱:{{name}}</h2>
<h2>學(xué)校地址:{{address}}</h2>
</div>
`,
data(){
return {
name:'幼兒園',
address:'一個(gè)城市'
}
}
});
const hello =Vue.extend({
template:`<div>你好呀纱意!</div>`,
})
//全局注冊(cè)組件
Vue.component('hello',hello)
new Vue({
el:'#root',
//第二步:局部注冊(cè)組件
components:{student,school}
})
new Vue({el:'#root2'})
</script>
</body>
</html>
知識(shí)點(diǎn)
- 模塊
(1):向外提供特定功能的js程序婶溯,一般就是一個(gè)js文件。
(2):為什么偷霉?js文件很多很復(fù)雜迄委。
(3):復(fù)用js,簡(jiǎn)化js的編寫(xiě)类少,提高js的運(yùn)行效率叙身。 - 組件
(1):用來(lái)實(shí)現(xiàn)局部功能的代碼集合(js,css,html,image....)
(2):為什么?一個(gè)界面的功能很復(fù)雜硫狞。
(3):復(fù)用代碼信轿,簡(jiǎn)化項(xiàng)目編碼,提高運(yùn)行效率残吩。 - 單文件組件
一個(gè)文件中只包含一個(gè)組件财忽。 - 非單文件組件
一個(gè)文件中包含n個(gè)組件。 - vue中使用組件的三大步驟
1:定義組件(創(chuàng)建組件)
2:注冊(cè)組件
3:使用組件(寫(xiě)個(gè)組件的標(biāo)簽) - 如何定義一個(gè)組件
使用Vue.extend({options}),其中options和new Vue時(shí)傳入的options幾乎一樣世剖,但也有點(diǎn)區(qū)別:
區(qū)別如下:
(1):el不要寫(xiě)定罢,為什么?最終所有的組件都要由vm管理旁瘫,服務(wù)于哪個(gè)容器由vm決定祖凫。
(2):data必須寫(xiě)成函數(shù)的形式琼蚯?避免組件被引用時(shí),數(shù)據(jù)存在引用關(guān)系惠况。 - 如何注冊(cè)一個(gè)組件
(1):局部注冊(cè):通過(guò)new Vue的components配置項(xiàng)遭庶。
(2):全局注冊(cè):通過(guò)Vue.component('組件名',組件)