组件的挂载
- import ComA from ‘@/component/comA’ (引入)
- components:{ ComA:ComA} (注册)
- <comA></comA> (挂载)
component 标签
使用component标签可以通过is属性来具名的显示对应的组件。
//将显示对应的组件
<component is='header'></component>
<component :is='变量'></component>
插槽 slot
在组件中设置插槽<slot />
,可以在使用组件的时候设置插槽里面的内容,方便自定义数据。
//组件
<div>
<slot name="title"/>
<slot />
</div>
//使用组件
<dialog>
<template slot='title'>自定义标题</template>
除了具名的插槽其余剩下写的内容都会显示在<slot />中
</dialog>
具名插槽需要在调用组件的时候使用 template
标签,slot
属性对应具体插槽的名称。
未具名的插槽,将显示为调用组件时其余的数据。
组件间相互通信
父传子
1.土方法
父->子
<div>
父级
<input type="button" value="+1" @click="fn()" />
</div>
<child ref="c1"/>
fn(){
this.$refs.c1.a();
this.$refs.c1.num++;
}
2.props(常用)
父级
<child :title="title"/>
子级
<template>
<div>
子级
<div>
接受到的title:{{title}}
</div>
</div>
</template>
export default {
props:['title'], 这里
data () {
return {
};
}
}
子传父
1.土办法
子->父
<div>
父级
{{xxx}}
</div>
<child :parent='this' />
props:['parent']
fn(){
this.parent.xxx++
}
不管是子传父 还是父传子 土办法是最简单的办法,但耦合度非常高,父子级绑定到一起没法拆开,但我们的组件一般都是希望能各自独立,并且可以相互配合。
2. $emit
子级
fn(){
this.$emit('getname',this.name)
}
父级
<child :title="title" @getname="nameValue"/>
methods: {
nameValue(value){
this.name = value
}
}
兄弟组件传值
1. bus
bus.js
import Vue from 'vue';
export default new Vue
brother1
fn(){
Bus.$emit('send',this.a);
}
brother2
created(){
const _this = this
Bus.$on('send',function(val){
_this.a = val;
})
}
2.vuex
通过状态管理,来实现组件间数据传递 ,vuex下篇文章里会系统的整理一下。