Vue组件间通信方式

组件可以封装一些重用的代码,通过传入不同的数据,实现组件的复用。组件之间传递数据基本上可以分为三种:父子组件、兄弟组件、隔代组件(跨组件),针对不同场景,我们可以选择不同的方式,具体如下:

父子组件通信:

(1)props/$emit

父组件通过自定义属性传递数据,子组件通过props来接收;

子组件通过emit传递一个自定义事件,父组件通过自定义事件来操作相应的逻辑:

父组件:

<template>
    <AppButton :btnContent="'下一步'" @commit="commit()"></AppButton>
</template>

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

@Component({
    components: {
        AppButton
    }
})
export default class EmergencyContact extends Vue {

    commit(): void {
        this.$router.push('loan-check');
    }
}
</script>

*******************************************************************************


子组件:

<template>
    <ion-button expand="block" class="px-3" :disabled="disabled" @click="commit()">
        <template v-if="btnContent">{
  {btnContent}}</template>

        <template v-else>-</template>
    </ion-button>
</template>

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

@Component({
    components: {}
})
export default class AppButton extends Vue {
    @Prop() disabled!: boolean;
    @Prop() btnContent!: string;

    @Emit('commit')
    commit() {}
}
</script>

 

(2)$parent/$children

子组件通过$parent访问父组件实例;父组件通过$children访问子组件实例:

父组件:

<template>
    <div class="h-100"&
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值