組件用component表示 是vue最強(qiáng)大的功能之一 組件化開發(fā)
組件可以擴(kuò)展HTML元素,封裝可重用的代碼
組件系統(tǒng)讓我們可以用獨(dú)立可復(fù)用的小組件來構(gòu)建大型應(yīng)用干花,幾乎任意類型的應(yīng)用的界面都可以抽象為一個(gè)組件樹:
image
組件分為全局組件和局部組件
全局組件
Vue.component("組件名"爽蝴,{
template:`代碼`
})
局部組件
new Vue({
el:"選擇器名"黍图,
components:{
組件名:"代碼"
}
})
例子
點(diǎn)擊是實(shí)現(xiàn)文字的切換
``html
<div class="box">
<chi></chi>
</div>
<script src="js/vue.js"></script>
``js
<script>
Vue.component("chi",{
template:`
<div>
<p>{{msg}}</p>
<button @click="add">點(diǎn)擊</button>
</div>
`,
data:function(){
return{
msg:"菜鳥教程",
flag:true
}
},
methods:{
add:function(){
if(this.flag){
this.msg="hello vue";
this.flag=false;
}else{
this.msg="菜鳥教程";
this.flag=true;
}
}
}
})
new Vue({
el:".box"
})
</script>
組件之間的傳值
組件傳值分為父傳子纤泵、子傳父、同級(jí)互傳
父傳子:
``html
<div class="box">
<chi></chi>
</div>
<script src="js/vue.js"></script>
<script>
Vue.component("chi",{
template:`
<div>
<h1>{{ddd}}</h1>
<he v-bind:mmm="msg"></he>
</div>
`,
data:function(){
return{
msg:"gcuyxhm",
ddd:"菜鳥教程"
}
}
})
Vue.component("he",{
props:["mmm"],
template:`
<div>
<h2>菜鳥教程</h2>
<p>{{mmm}}</p>
</div>
`
})
new Vue({
el:".box"
})
</script>
、
顯示為:
菜鳥教程
菜鳥教程
gcuyxhm
用父傳子實(shí)現(xiàn)列表
<style>
*{
margin: 0px;
padding: 0px;
list-style: none;
text-decoration: none;
}
</style>
<div class="box">
<chi></chi>
</div>
<script src="js/vue.js"></script>
<script>
Vue.component("chi",{
template:`
<div>
<he v-bind:mmm="msg"></he>
<wan v-bind:ttt="arr"></wan>
</div>
`,
data:function(){
return{
arr:["蘋果","香蕉","鴨梨"],
msg:"水果"
}
}
})
Vue.component("he",{
props:["mmm"],
template:`
<h2>{{mmm}}</h2>
`
})
Vue.component("wan",{
props:["ttt"],
template:`
<ul>
<li v-for="value in ttt">{{value}}</li>
</ul>
`
})
new Vue({
el:".box"
})
</script>
顯示為:
水果
蘋果
香蕉
鴨梨
子傳父:
<div class="box">
<one></one>
</div>
<script type="text/javascript" src="js/vue.js" ></script>
<script>
Vue.component("one",{
template:`
<div>
<h3>我叫{{mmm}}</h3>
<two @btn="alt"></two>
</div>
`,
data:function(){
return{
mmm:""
}
},
methods:{
alt:function(ttt){
this.mmm=ttt;
}
}
})
Vue.component("two",{
template:`
<div>
<input type="text" v-model="txt" />
<button @click="add">點(diǎn)擊</button>
</div>
`,
data:function(){
return{
msg:"",
txt:""
}
},
methods:{
add:function(){
this.msg=this.txt
this.$emit("btn",this.txt)
this.txt=""
}
}
})
new Vue({
el:".box"
})
</script>
注:
prop(用于父傳子)
prop 是父組件用來傳遞數(shù)據(jù)的一個(gè)自定義屬性。
父組件的數(shù)據(jù)需要通過 props 把數(shù)據(jù)傳給子組件刘离,子組件需要顯式地用 props 選項(xiàng)聲明 "prop"
$emit( event, […args] )(用于子傳父)
觸發(fā)當(dāng)前事件。附加參數(shù)都會(huì)傳給監(jiān)聽器回調(diào)睹栖。
子組件通過$emit來觸發(fā)事件硫惕,將參數(shù)傳遞出去