vue3.0+typescript 教程之父子传值

效果图:

上代码:

父组件代码:

<template>
    <div class="demo01-container">
        <div class="parent-sty">
            <el-input v-model="name" style="width: 20%;margin-bottom: 2%"/>
            <div>子组件点击次数: {{clickCount}}</div>
        </div>

        <div class="child-sty">
            <child-component :name='name' @handleChild='handleChild'/>
        </div>

    </div>
</template>

<script lang="ts">
    /* eslint-disable */
    import {Component, Vue} from "vue-property-decorator";
    import childComponent from "./child/demo01-child.vue";

    @Component({
        name: "childParent",
        components: {
            childComponent
        }
    })
    export default class Demo01 extends Vue {
        private firstName: string = "Jone";
        private lastName: string = "Doe";
        private clickCount: number = 0;

        get name() {
            return this.firstName + " " + this.lastName;
        }

        set name(value) {
            const splitted = value.split(" ");
            this.firstName = splitted[0];
            this.lastName = splitted[1] || "";
        }

        handleChild(count: number): void {
            this.clickCount = count;
            console.log(this.clickCount);
        }
    }
</script>

<style scoped lang="sass">
    .demo01-container
        width: 100%

        .parent-sty
            width: 100%
            height: 200px
            border-bottom: 1px solid #cccccc

        .child-sty
            width: 100%
            height: 200px
            padding: 2% 0

</style>

子组件代码:

<template>
    <div>
        <div style="margin-bottom: 2%">父组件传递的值:{{name}}</div>
        <el-button type="primary" @click="handleClick">点击传递给父亲</el-button>
    </div>
</template>

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

    @Component
    export default class demo01Child extends Vue {
        private count: number = 0;
        @Prop({default: ""}) private name!: string;   // !: 表示一定存在   ?: 表示可能不存在。这两种在语法上叫赋值断言

        handleClick() {
            this.count ++;
            this.$emit('handleChild', this.count)
        }
    }
</script>

<style scoped>

</style>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值