组件:
1.组件化思维:
组件化针对的是页面中的整个功能模块的划分。(好比在日常中的项目分工)
2.组件的概念:
组件是一个html, css, js, images等外链资源,这些部分组成一个聚合体。
如:bootstrap的使用
3.组件的优点:
代码的复用性比较高,便于维护
划分组件的原则: 复用率高,独立性强。
vue中如何定义,使用,操作组件:
组件:
1.vue.extend()
2.vue.component() 为什么要执行这个方法:
组件的表现形式是标签,组件想要合法,必须注册。
组件的注册分为两种:全局注册和局部注册。
局部注册:
<div id="app">
<txt></txt>
</div>
<script>
new Vue({
el : '#app',
components : {
'txt' : {
template : '<div>德玛西亚</div>'
}
}
})
</script>
全局注册:
<div id="app">
<txt></txt>
</div>
<script>
var txt = Vue.extend({
template : '<div>德玛西亚</div>'
})
Vue.component('txt', txt)
new Vue({
el : '#app',
})
组件的嵌套:
在全局注册中:
子组件必须以标签的形式放在父组件的tempalte选项中
<div id="app">
<father></father>
</div>
<script>
Vue.component('father',{
template : '<h3> father <son></son> </h3>'
})
Vue.component('son',{
template : '<h3> son </h3>'
})
new Vue({
el : '#app'
})
</script>
在局部中:
子组件必须在父组件中注册之后才能在父组件的模板中使用
<div id="app">
<Father></Father>
</div>
<script>
new Vue({
el : '#app',
components:{
'Father' : {
template : '<div> father <son></son> </div>',
'son' : {
template : '<div> son </div>'
}
}
}
})
</script>
需要注意的是:在全局注册中,组件需要书写在根元素的上面,不然会报错。
template外用:
<div id="app">
<txt></txt>
</div>
<template id="content">
<p>德玛西亚万岁</p>
</template>
<script>
Vue.component("txt",{
template : '#content'
})
new Vue({
el : "#app"
})
</script>
值得一提的是组件模板中的根元素是唯一的。
<div id="app">
<txt></txt>
<template>
<p>德玛西亚</p>
</template>
</div>
<template id="content">
<div>
<p>诺克萨斯</p>
<p>诺克萨斯</p>
<p>诺克萨斯</p>
<p>诺萨克斯</p>
</div>
</template>
<script>
Vue.component('txt',{
template : "#content"
})
new Vue ({
el : '#app'
})
</script>
总结:
1.组件的template如果在body里面的话,一定记住要放在 #app 的div外
2.组件的template在body中使用的话, 是不会解析的, 但是组件内的template是会解析的
3.组件的模板中的直接子元素必须有一个, 如果你要有多个, 必须使用v-if v-else-if
组件中的data选项
直接看代码:
<div id="app">
<txt></txt>
</div>
<template id="content">
<div>
{{ msg }}
</div>
</template>
<script>
Vue.component('txt',{
template: '#content',
data(){
return {
msg : "艾欧尼亚"
}
}
})
new Vue({
el : "#app",
data : {}
})
</script>
跟实例中data是一个对象,在组件中data是一个函数,且组件的data必须有返回值,返回值
一定是一个对象
函数的作用:
1. 函数有独立作用域
2. 函数可以有return 返回值