六、组件(全局 / 局部)
6.1 全局组件
- 1.创建组件构造器
注意:组件模板要有根元素包裹
// peofile是组件构造器名称
let profile = Vue.extend({
template: `
<div>
<p>我是组件我是组件</p>
</div>
`
})
- 2.注册组件
Vue.component( '组件名称', 组件构造器名称 )
- 3.使用组件
<abc></abc>
或者可以把1和2融为一步
Vue.component('abc', {
template: `
<div>
<p>我是组件我是组件</p>
</div>
`
})
可以把字符串模板换成art-template
<script id="info" type="text/html">
<div>
<p>我是组件我是组件</p>
<div>
</script>
Vue.component('abc', {
template: "#info"
})
- 4.Vue中专门提供了编写模板的标签template
<template id="info">
<div>
<p>我是组件我是组件</p>
<div>
</template>
Vue.component('abc', {
template: "#info"
})
6.2 局部组件
和全局组件一样,也是需要创建组件构造器,注册组件,在vue对象中新增一个components的key,再使用组件。不过局部组件只能在对应的vue实例范围内使用
<script>
let vue = new Vue({
el: '#app',
data: {
},
components: {
'组件名称': {
template: "#info"
}
}
});
</script>
6.3 组件中的data和 methods
- 组件中的data必须是一个函数,返回一个对象,把数据放在对象里
为什么data必须是一个函数??
组件中的data如果不是通过函数返回的,那么多个组件就会公用一份数据,就会导致数据混乱。如果组件中的data是通过函数返回的,那么每创建一个组件,就会调用一次函数,把这个函数返回的数据和当前调用的组件绑定在一起,就可以避免数据混乱(没讲清楚,周末单独看一下为什么data要是个函数?)
6.4 动态切换组件
使用< component v-bind:is=“组件名称” > 标签v-bind绑定显示,要记录组件的状态,要把component标签放在keep-alive标签中(keep-alive还不太了解,之后再学习)
七、父子组件
- 7.1 什么是父子组件?
在组件中定义了另一个组件,这样的结构叫父子组件 - 7.2 父子组件数据的传递
把要传递的数据绑定到子组件上,在子组件中通过props: [‘绑定的数据名称1’, ‘绑定的数据名称2’]来接收,就可以在子组件中使用父组件中传递过来的数据了 - 7.3 父子组件方法的传递
把父组件中的方法通过v-on绑定给子组件,子组件监听自身事件,在自身事件中通过this.$emit()来接收传递过来的方法
<div id="app">
<father></father>
</div>
<template id="father">
<div>
<p>我是爸爸组件</p>
<p>{{ name }} : {{ age }}</p>
<button @click="farfn">父组件中的按钮</button>
//把父组件中的数据绑定v-bind 给子组件
//把父组件中的方法传递v-on 给子组件
<son :msg="name" :msg2="age" @sonfn="farfn"></son>
</div>
</template>
<template id="son">
<div>
<p>我是儿子组件</p>
//使用传递的数据
<p>我是从父组件传递过来的---{{msg}}:{{msg2}}</p>
//监听子组件的点击事件
<button @click="sonclick">子组件中的按钮</button>
</div>
</template>
<script>
Vue.component("father",{
template: "#father",
data(){
return{
name: 'liyinhe',
age: 21
}
},
methods:{
farfn(){
alert("我弹出来啦~~")
}
},
components: {
'son': {
template: '#son',
//接收传递的父组件数据
props:["msg", "msg2"],
methods:{
sonclick(){
// 通过this.$emti("子组件传递的事件")来接收父组件中的事件
this.$emit("sonfn")
}
}
}
}
});
let vue = new Vue({
el: '#app',
});
</script>
- 7.4 子组件传递数据给父组件
刚刚学了父组件传递方法给子组件,子组件要传递数据给父组件,就是通过刚刚传递的方法来传递数据的
<template id="father">
<div>
<p>我是爸爸组件</p>
<button @click="farFn">父组件中的按钮</button>
<son @sonfn="farFn"></son>
</div>
</template>
<template id="son">
<div>
<p>我是儿子组件</p>
<button @click="sonClick">子组件中的按钮</button>
</div>
</template>
<script>
Vue.component("father",{
template: "#father",
methods:{
//接收参数
farFn(data){
console.log(data);
}
},
//子组件
components: {
'son': {
template: '#son',
methods:{
sonClick(){
//通过这个传递参数
this.$emit("sonfn", "直播与");
}
}
}
}
});
let vue = new Vue({
el: '#app',
});
</script>
- 7.5 组件命名注意点
- 在注册组件时使用了驼峰命名法,在使用时要使用短横线分隔命名,如组件命名时为 myFarther,在使用时要用 < my-farther >
- 在父子组件传递数据时,接收数据时想使用驼峰命名,在父组件中绑定数据给子组件时应该使用短横线命名
- 在组件中传递方法时不可以使用驼峰命名,只能使用短横线命名
- 7.6 多级传递
爷爷组件要传递数据和方法给孙子组件,只能先传递给爸爸组件,再传递给孙子组件