父/子组件传值

父组件向子组件传值

首先先创建两个组件一个作为父组件,一个作为子组件。

创建两个组件一个是text.vue一个是demo.vue。(至于没有用father /son 以及 parent/child 这些名字是因为之前自己把子父组件也给弄混淆了。注:子组件是包含在父组件之中的)

demo.vue为父组件

<template>
    <div class="demo">
        <h1>demo为父组件</h1>
        <div style="border:solid 1px red;width:500px;height:400px;">
            <h2>父组件向子组件传值</h2>
            <h2>绿框中为子组件内容</h2>
            <v-text :mz="name" style="border:solid 1px green;"></v-text>
        </div>
    </div>
</template>

<script>
import vText from "./text.vue";
export default {
    components: {
        vText
    },
    data() {
        return {
            name:'小明'
        };
    }
};
</script>

<style scoped>
</style>

text.vue为子组件

<template>
    <div class="text">
        <h1>text为子组件</h1>
        <h2 style="color:red;">{{mz}}</h2>
    </div>
</template>

<script>
export default {
    props: ["mz"],//方式一

    //方式二
    // props:{
    //     mz:String
    // },

    //方式三
    // props:{
    //     mz:{
    //         type:String,
    //         default:''
    //     }
    // },
    data() {
        return {};
    }
};
</script>

<style scoped>
</style>

text中的方式一二三是获取数据的三个方式。props中的mz(名字)是父组件中<v-text>中的":mz",在父组件(demo.vue)中可以看出name或者说“小明”是父组件的参数并且这个参数在子组件中是没有的,但看下面的效果图可以看到,这个值在子组件的内容区内显示出来了,说明值传递成功,在子组件中可以随意引用。

子组件向父组件中传值

父组件demo.vue

<template>
    <div class="demo">
        <h1>demo为父组件</h1>
        <div style="border:solid 1px red;width:500px;height:400px;">
            <h2>子组件向父组件传值</h2>
            <h2>绿框中为子组件内容</h2>
            <v-text @test="change" style="border:solid 1px green;"></v-text>
            <h2>父组件获取子组件的值:</h2>
            <h3 style="color:green;">age:{{ages}}</h3>
        </div>
    </div>
</template>

<script>
import vText from "./text.vue";
export default {
    components: {
        vText
    },
    data() {
        return {
            ages:''
        };
    },
    methods:{
        change(age){
            this.ages = age;
        }
    }
};
</script>

子组件text.vue

<template>
    <div class="text">
        <h1>text为子组件</h1>
        <el-button @click="testClick">点击</el-button>
    </div>
</template>

<script>
export default {
    data() {
        return {
            age:30,
        };
    },
    methods:{
        testClick(){
            this.$emit('test',this.age)
        }
    },
};
</script>

为了方便区分,在父组件中data使用了ages,在子组件中有个数据为age值是30,当点击按钮后触发方法把值传到父组件中去。

点击前                                                                                                       点击后

猜你喜欢

转载自blog.csdn.net/youyanh/article/details/81539826