1.什么是组件嵌套?
所谓组件嵌套 就是在子组件的父级模板中 用标签的形式调用子组件
在下面这段代码中app这个<div>是最大的的父级,他所包裹着的子组件都有自己的模板 并且根据id相互连接但是自组建的数据只能在他们的内部实现,需要在他们每个组件的父级下进行注册用下面这种方法,并且在他们的父级内部用标签的形式调用
components:{
xxx:xxx
}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./../js/vue.js"></script> </head> <body> <div id="app"> {{msg}} <son> </son> </div> </body> </html> <template id="son"> <div> {{msg1}} <soner> </soner> </div> </template> <template id="soner"> <div> {{msg2}} </div> </template> <script> var Soner={ template:"#soner", data:function () { return{ msg2:"子组件的子组件" } } } var Son={ template:"#son", data:function () { return{ msg1:"子组件" } }, components:{ soner:Soner } } var app=new Vue({ el:"#app", data:{ msg:"根组件" }, components:{ son:Son } }) </script>
2.怎么使用组件通讯?
组建通讯用通俗的话来讲就是父级子级等相互嵌套关系之间的数据传递,比如父组件的数据给子组件、子组件的数据给父组件用、人为触发 自定义组件、动态组件.....
关于父组件传递数据给子组件首先接触到的是props,首先在父组件调用的子组件内添加一条自定义属性
<sunzi :bb="msg1"> </sunzi>
之后在该组件内添加props
var Sunzi={
template:"#sunzi",
props:["bb"],
data:function () {
return{
msg2:"hello"
}
}
最后只需要用Mounted(钩子函数内的加载属性)更改里面的值就好了
var Sunzi={
template:"#sunzi",
props:["bb"],
data:function () {
return{
msg2:"hello"
}
},
mounted(){
this.msg2=this.$props.bb;
}
}
总的来说就是利用了父子组件之间的标签进行关联,然后在子组件标签上所有的属性构成的集合在子组件的props属性可以接收到
父组件获取子组件的数据用到的是refs
首先还是在子组件内部写入refs属性
<sunzi ref="xiaoli"> </sunzi>
然后在父组件下使用$this.refs
var Laoda={
template:"#laoda",
data:function () {
return{
msg1:"hello"
}
},
components:{
sunzi:Sunzi
},
mounted(){
console.log(this.$refs.xiaoli.msg2)
this.msg1=this.$refs.xiaoli.msg2;
}
}
这样父组件就可以接收到子组件的数据
人为触发的自定义事件 在子组件下定义一个事件 创建方法是this.$emit
<template id="sunzi"> <div > 子组件 <button @click="fn">自定义</button> </div> </template> <script> var Sunzi={ template:"#sunzi", props:["bb"], data:function () { return{ msg2:"hello" } }, methods:{ fn(){ this.$emit("aa","自定义事件") } } }
然后在子组件内用@去接收事件
<template id="laoda"> <div> 父组件 {{msg1}} <sunzi @aa="ss"> </sunzi> </div> </template>
在父组件内写方法
var Laoda={
template:"#laoda",
data:function () {
return{
msg1:"大大"
}
},
components:{
sunzi:Sunzi
},
methods:{
ss(res){
this.msg1=res;
}
}
最后动态组件需要一个vue中的一个组件
<component v-bind:is="ss"></component>
这个组件有一个is属性用来动态切换绑定的ss值
var Laoda={
template:"#laoda",
data:function () {
return{
msg1:"hello",
ss:"yule",
arr:["yule","xinwen","tiyu"]
}
},
methods:{
fn(i){
this.ss=this.arr[i];
}
},
components:{
yule:Yule,
xinwen:Xinwen,
tiyu:Tiyu
}
}
this.$emit