vue ts父组件使用ref调用子组件的方法或获取子组件的值

vue2.0 ts父组件使用ref调用子组件的方法和值

父组件中用ref绑定子组件,然后通过this.$refs.名字就可以获取子组件的值或调用相关方法。
父组件

<template>
  <div>
    <div class="parent">
      <h1>父组件名字:{{parentName}}</h1>
       <a-button type="primary" size="large" @click="refGetChildValue">
         使用ref调用子组件的值
        </a-button> 
        <div class="ref-function">
        <a-button type="primary" size="large" @click="refGetChildFunction">
         使用ref调用子组件的方法
        </a-button> 
        </div>
    </div>
   
    <Child
      ref="child"
     />
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import Child from '@/components/Child.vue';

@Component({
  components: {
    Child
  },
})
export default class Home extends Vue {
  parentName:string='父组件'
  childEmitValue:any='';
  //ref获取子组件的值
  refGetChildValue(){
    alert(this.$refs.child.childValue);
  }
  //ref调用子组件的方法
  refGetChildFunction(){
    this.$refs.child.childFunction();
  }
}
</script>

子组件

<template>
  <div>
    <div class="child">
      <div>
        <h1>子组件</h1>
       
      </div>
      <div class="search">
        <a-input-search
          placeholder="传值给父组件"
          enter-button="Emit传值给父组件"
          size="large"
          @search="onSearch"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop,Emit } from "vue-property-decorator";

@Component({
  components: {},
})
export default class Child extends Vue {
  childValue:string="在路上,不需此行";
    onSearch(value:any) {
      console.log(value);
      this.$emit('getChildInput',value);
    }

    childFunction(){
      alert('我是子组件的方法');
    }
}
</script>

ref获取子组件值效果图
在这里插入图片描述ref调用子组件方法效果图
在这里插入图片描述

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值