1、父组件向子组件传值

父组件

<template>
    <div class="home">
        <Child :parentValue="msg"></Child>
    </div>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import Child from "@/components/Child.vue";
@Options({
    components: {
        Child
    }
})
export default class Home extends Vue {
    msg = "父组件向子组件传递的值";
}
</script>

子组件:

<template>
    <div>
        <div>{{ parentValue }}</div>
    </div>
</template>
<script lang="ts">
import { Options, Vue } from "vue-class-component";
import { Prop } from "vue-property-decorator";

@Options({})
export default class Child extends Vue {
    @Prop(String) //括号里为父组件传过来的值的类型
    private parentValue = ""; //父组件传过来的值用parentValue接收,默认为空
}
</script>

2、子组件向父组件传值

父组件

<template>
    <div class="home">
        <!-- 方法一-->
        <Child @handleAdd1="handleChildValue"></Child>
        <!-- 方法二-->
        <Child @test="handleChildValue"></Child>
        <!-- 方法三-->
        <Child @handleAdd3="handleChildValue"></Child>
    </div>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import Child from "@/components/Child.vue";
@Options({
    components: {
        Child
    }
})
export default class Home extends Vue {
    childValue = "";
    // 处理子组件传过来的值  val:是自定义的
    private handleChildValue(val: string) {
        this.childValue = val;
    }
}
</script>

子组件

<template>
    <div>
        <!-- 方法一:直接调用@Emit -->
        <button @click="handleAdd1">点我向父组件传值</button>
        <!-- 方法二:直接调用@Emit -->
        <button @click="handleAdd2">点我向父组件传值</button>
        <!-- 方法三:间接调用@Emit -->
        <button @click="handleAdd3">点我向父组件传值</button>
    </div>
</template>
<script lang="ts">
import { Options, Vue } from "vue-class-component";
import { Emit } from "vue-property-decorator";

interface ITest {
    param1: string;
    param2: number;
    say: (age: number) => string;
}
@Options({})
export default class Child extends Vue {
    @Prop(String) //括号里为父组件传过来的值的类型
    private parentValue = ""; //父组件传过来的值用parentValue接收

    private toParent = "要传递给父组件的值";
    // 方法一
    @Emit()
    handleAdd1(): string {
        return this.toParent; //return 将要传递的值
    }
    // 方法二
    // 这时父组件接收值时是用@Emit('test')中的test接收的
    @Emit("test")
    handleAdd2(): string {
        return this.toParent;
    }
    // 方法三
    // 先定义父组件接收的方法
    @Emit()
    handleAdd3(): string {
        return this.toParent; //return将要传递的值
    }
    handleClickEvent(): void {
        // ...一些其他的操作
        // 然后手动调用传值
        this.handleAdd3();
    }

    // 子组件向父组件传递多个值,建议把这个值封装成一个对象,然后一起传递
    // eg: (子组件)
    @Emit()
    test(): ITest {
        // 要传给父组件的多个值
        const params = {
            param1: "hello",
            param2: 111111,
            say(age: number): string {
                return `${age}+is good`;
            }
            // ......
        };
        return params;
    }
}
</script>
Logo

前往低代码交流专区

更多推荐