vue.js(16)--vue的组件

注册一个全局组件

<div id="app">
    <test></test>
</div>
 
<script>
// 注册全局组件
Vue.component('test', {
  template: '<h1>自定义组件!</h1>'
})
// 创建根实例
new Vue({
  el: '#app'
})
</script>

创建一个局部组件(只能在父模板中使用)

<div id="app">
    <test></test>
</div>
 
<script>
var Child = {
  template: '<h1>自定义组件!</h1>'
}
new Vue({
  el: '#app',
  components: {
    'test': Child
  }
})
</script>

 组件化和模块化的区别:

模块化是从后台代码逻辑角度出发,方便代码分层开发,保证每个功能模块的职能单一

组件化是从UI界面的角度进行划分的,前端的组件化方便UI组件的重用

<body>
<div class="app">
<my-com1></my-com1>
<my-com2></my-com2>
<my-com3></my-com3>
<my-com4></my-com4>
<mycom5></mycom5>
<!-- 注意如果注册组件时使用驼峰命名,需要大写改小写,并加上‘-’ -->
</div>
<template id="tmp1">
<div>
<h1>我是第四个全局组件</h1>
</div>
</template>
<template id="tmp2">
<div>
<h1>我是第yi个私有组件</h1>
</div>
</template>
<script>
var com1=Vue.extend({
template:"<h1>我是第一个全局组件,使用的是vue.extend</h1>"
})

Vue.component('myCom1',com1)
Vue.component('my-com2',Vue.extend({
template:'<h1>我是第二个全局组件</h1>'
}))

Vue.component('my-com3',{
template:'<div><h1>我是第三个全局组件</h1><h1>{{msg}}</h1></div>',
data:function() {
return({
msg:'hahahah'
})
}
})//无论是哪种创建组件的方式,在templa中必须有且只有一个根元素

Vue.component('my-com4',{
template:'#tmp1'
})
var vm = new Vue({
el:'.app',
components:{
mycom5:{
template:'#tmp2'
}
}
})
</script>

</body>
posted @ 2019-08-17 22:18  齐齐怪  阅读(148)  评论(0编辑  收藏  举报