vue中--父组件调用子组件方法 ref实现 + ts内使用报错问题(断言解决)

开篇:最近需要编写一个组件互相传递消息,首先是父组件调用子组件方法并传值,在网上找到ref可以实现那么开始搞。

vue  ref  调用子组件的方法(原生)

定义子组件son.vue

组件内定义方法

methods:{
    showToast(msg){
        console.log(msg)
    }
}

父组件引入子组件,并声明ref

父组件里面的方法通过ref执行子组件的方法

<template>
    <view>
        <view @click="show">点击我传递信息</view>
        <son ref="readmy"></son>
    </view>
</template>

<script>
    import Son '@/components/son.vue';
    export default {
        components: { Son },
        methods:{
            show(){
                this.$refs.readmy.showToast("我是传递过去的信息");    
            }
        }
    }
</script>

vue  ref  调用子组件的方法(TS)

这里我引入了两个插件,一个 TypeScript  /  第二个 vue-property-decorator (尤大大推出用类的方式写ts)

这里创建一个son.vue

<template>
    <div>我是son.vue</div>
</template>
<script lang="ts">
    import {Component, Prop, Vue} from "vue-property-decorator";

    @Component({})
    export default class Son extends Vue{
       sendMsg(msg) {
           console.log(msg)
       }
    }
</script>

父组件引入子组件,并声明ref

父组件里面的方法通过ref执行子组件的方法

<template>
    <div>
        <div @click="sendMessage">点击我传递信息</div>
        <son ref="readmy"></son>
    </div>
</template>

<script lang="ts">
    import {Component, Vue} from "vue-property-decorator";
    import Son from "../../component/Son.vue";

    @Component({ components: { Son} })
    export default class Log extends Vue {
        sendMessage() {
           this.$refs.readmy.sendMsg('我是点击传递过来的数据啊')
        }
    }
</script>

然后我满心期待运行,然后就报错了....

what the fuсk!!!!

这个问题困扰了我一整天,在百度也没遇到和我有一样问题的人。

然后第二天早晨睡醒就想出来了,这说明有问题解决不了需要多睡觉。

写这篇博客就是希望和我遇到一样问题的人能翻到我的博客。能帮助到你们。

断言,把数据断言成----子类类型

setTimeout(() => {
   (this.$refs.mainIframe as Son).sendMsg('我是点击传递过来的数据啊')
   console.log(this.$refs.mainIframe)
}, 2000);

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值