组件

组件是什么?
组件是Vue.js最强大的功能之一,组件可扩展Html元素,封装可重用的代码。
组件分为两大类:全局组件和局部组件。
组件中的date选项必须是一个函数,必须要有一个返回值,组件中的模板必须包含一个根元素(父元素)
组件是可以被嵌套的。
组件之间的传值:
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>

5.png

全局组件实例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:"我是组件中的内容"
}
},
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>
6.png

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容