组件通讯(vue)

一、属性传值

1.可传值类型

  • 固定值
  • 绑定属性
  • 方法
  • 本类对象

2.操作步骤

①.父组件调用子组件的时候,绑定动态属性 <htitle mess="父组件给子组件传值"></htitle>

②. 在子组件里边通过props,接收父组件传过来的值

3.适用场景

仅适用于 父组件给子组件传值

4.属性介绍

组件属性定义:

 

 props:["mess","bindMsg","run","fatherThis"],

子组件验证也可传入参数的合法性:

 

 props:{
        'mess':String,
        'bindMsg':[String, Number],
        'run':Function, 
        'fatherThis':Object,
}

 

5.示例代码

父组件:

 

<template>
  <div id="app">
    <htitle mess="父组件给子组件传值了" :bindMsg="msg" :run="run" :fatherThis="this"></htitle>
  </div>
</template>

子组件

 

<template>
    <div class="divfirst">
        <span>{{mess}}</span>
        <h1>{{bindMsg}}</h1>
        <button @click="run()">点击调用父组件方法</button>
        <button @click="getPrasent()">点击获取父组件实体(实体拿到可以使用用父组件的方法和属性了)</button>
    </div>
</template>

<script>
export default {
    props:{
        'mess':String,
        'bindMsg':[String, Number],
        'run':Function, 
        'fatherThis':Object,
    },
    data(){
        return {}
    },
    methods:{
        getPrasent(){
            this.fatherThis.run();
            alert(this.fatherThis.msg);
        } 
    }
}
</script>

二、父组件获取子组件数据

 父组件通过$refs获取子组件的数据和方法

1.可获取类型

  • 子组件属性
  • 子组件方法

2.操作步骤

1.调用子组件的时候调用一个ref
<v-fgsheader ref="header"></v-fgsheader>
2.在父组件中通过
this.$refs.header.属性
this.$refs.header.方法

3.适用场景

子组件给父组件传值

4.示例代码

父组件

 

<template>
    <div class="FGSHome">
        <v-fgsheader ref="header"></v-fgsheader>
        <button @click="getChildProp()">获取子组件的属性的值</button>
        <button @click="getChildMethod()">获取子组件的方法</button>
    </div>
</template>

<script>
import FGSHeader from './FGSHeader.vue'
    export default{

        data(){
            return { }
        },
        components:{
            'v-fgsheader':FGSHeader,
        },
        methods: {
          getChildProp(){
              alert(this.$refs.header.msg);
          },  
          getChildMethod(){
              this.$refs.header.run();
          }
        },
    }
</script>

子组件

 

<script>
    export default{
        data(){
            return {
                msg:"我是子组件header的值哟"
            }
        },
        methods:{
            run(){
                alert("这是子组件Header的方法+"+this.msg);
            }
        }
    }
</script>

三、子组件获取父组件数据

  子组件通过$parent获取父组件的数据和方法,这种传值方式实际上类似于上边的属性传值中父组件给子组件的传递了子类对象this,只不过Vue官方给封装好了。

1.可获取类型

  • 父组件属性
  • 父组件方法

2.操作步骤

直接在子组件中使用this.$parent.XX,不需要做任何多余操作。

3.适用场景

父组件给子组件传值

4.示例代码

子组件

 

getFatherProp(){
    alert(this.$parent.fatherMsg); 
},
getFatherMethod(){
    this.$parent.fatherRun();
}



 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值