vue学习(四)--- 组件

1.组件的挂载
2.component 标签
3.插槽 slot
4.组件间相互通信

组件的挂载
  1. import ComA from ‘@/component/comA’ (引入)
  2. components:{ ComA:ComA} (注册)
  3. <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下篇文章里会系统的整理一下。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值