組件(component): 是vue最強大的功能之一 組件化開發(fā)
組件可以擴展 HTML 元素菲盾,封裝可重用的代碼。
分為:全局痹栖; 局部
組件之間的傳值******
父傳子 用屬性傳
子傳父 用事件傳
同級之間傳值
組件1:
<!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>
<ul>
<li></li>
</ul>
</div>
<script src='js/vue.js'></script>
<script>
//全局:
Vue.component('my-component',{
template:`
<div>
<h1>這是一個組件</h1>
<ul>
<li>1111</li>
<li>1111</li>
<li>1111</li>
<li>1111</li>
</ul>
</div>
`
})
new Vue({
el:'#app',
// components:{
// 'my-component':{
// template:``
// }
// }
})
</script>
</body>
</html>
瀏覽器打開
圖片.png
組件2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='app'>
<!-- <p>{{msg}}</p>-->
<my-component></my-component>
</div>
<script src='js/vue.js'></script>
<script>
Vue.component("my-component",{
template:`
<div>
<h1>{{msg}}</h1>
<button @click='alt'>按鈕</button>
</div>
`,
data:function(){
return{
msg:'dcgf'
}
},
methods:{
alt:function(){
alert(11111)
}
}
})
new Vue({
el:'#app',
})
</script>
</body>
</html>
瀏覽器打開:
圖片.png
點擊按鈕:
圖片.png
組件3:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='app'>
<my-content></my-content>
</div>
<script src='js/vue.js'></script>
<script>
Vue.component("my-content",{
template:`
<div>
<h2>我是my-content組件的標題</h2>
<my-child v-bind:message='msg'></my-child>
</div>
`,
data:function(){
return{
msg:'dgddbghfghfnh'
}
}
})
Vue.component("my-child",{
props:['message'],
template:`
<div>
<h3>我是my-child組件中的標題</h3>
<p>{{message}}</p>
</div>
`
})
new Vue({
el:'#app'
})
</script>
</body>
</html>
組件4:水果列表
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='app'>
<my-father></my-father>
</div>
<script src='js/vue.js'></script>
<script>
Vue.component("my-father",{
template:`
<div>
<my-son v-bind:tit='title'></my-son>
<my-list v-bind:fruit='arr'></my-list>
</div>
`,
data:function(){
return{
arr:['apple','pear','orange'],
title:'水果列表'
}
}
})
//title
Vue.component('my-son',{
props:['tit'],
template:`
<h2>{{tit}}</h2>
`
})
//arr
Vue.component('my-list',{
props:['fruit'],
template:`
<ul>
<li v-for="value in fruit">{{value}}</li>
</ul>
`
})
new Vue({
el:'#app'
})
</script>
</body>
</html>
打開:圖片.png