组件(component): 是vue最强大的功能之一 组件化开发
组件可以扩展 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>
浏览器打开
![](https://img.haomeiwen.com/i14004990/744505bab0317e74.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>
浏览器打开:
![](https://img.haomeiwen.com/i14004990/f6996561e191560c.png)
点击按钮:
![](https://img.haomeiwen.com/i14004990/b3d3328146673571.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>
打开:
![](https://img.haomeiwen.com/i14004990/0eca3d4a334c114f.png)
网友评论