組件是什么陈莽?
組件是Vue.js最強大的功能之一,組件可擴展Html元素,封裝可重用的代碼走搁。
組件分為兩大類:全局組件和局部組件独柑。
組件中的date選項必須是一個函數(shù),必須要有一個返回值私植,組件中的模板必須包含一個根元素(父元素)
組件是可以被嵌套的忌栅。
組件之間的傳值:
1.父給子傳(用屬性傳)Props:【‘屬性名’】 子組件
2.子給父傳(用事件傳)自定義事件 $emit
3.同級之間傳值 (用第三方量)
全局組件實例1:
body部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<my-component></my-component>
<my-component></my-component>
<my-component></my-component>
<my-component></my-component>
<my-component></my-component>
<my-component></my-component>
<my-component></my-component>
</div>
js部分
<script src="js/vue.js"></script>
<script>
new Vue({
el:"#app",
data:{
msg:'jkjas'
},
methods:{},
computed:{},
filters:{},
components:{
'my-component':{
template:<div> <p> <a href='#'>去百度</a> </p> </div>
}
}
})
</script>
</body>
</html>
全局組件實例2:
body部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<my-component></my-component>
</div>
js部分:
<script src="js/vue.js"></script>
<script>
Vue.component('my-component',{
template:
<div> <h1>{{msg}}</h1> <button @click='alt'>點擊按鈕</button> <my-child></my-child> </div>
,data:function(){
return{
msg:"我是組件中的內(nèi)容"
}
},
methods:{
alt:function(){
alert("lhf")
}
}
})
Vue.component('my-child',{
template:
<div> <h3>我是第二個組件</h3> <p>lhflbxlgxlgy</p> </div>
})
new Vue({
el:"#app",
data:{},
methods:{}
})
</script>
</body>
</html>