关于vue的父子组件传值问题

创建三个vue组件——index.vue(父组件),son1.vue(子组件),son2.vue(子组件)

在router文件设置好父组件路径(子组件不用设置路由);
父子组件之间的页面转换是不通过路由的
父组件传递数据给子组件使用,遇到业务逻辑操作时子组件触发父组件的自定义事件。

this.$parent

此方式并不属于数据的传递而是一种主动的查找。父组件并没有主动的传递数据给子组件,而是子组件通过与父组件的关联关系,获取了父组件的数据。
该方法虽然能实现获取父组件中的数据但是不推荐这种方式,因为vue提倡单向数据流,只有父组件交给子组件的数据子组件才有使用的权限,不允许子组件私自获取父组件的数据进行使用。在父与子的关系中子应当是处于一种被动关系。

父组件内容:

<template>
  <div class="index">
    <div v-if='group_type==1'>
        <span>我是父组件</span>
        <button @click='group_type=4'>去大儿子家</button>
        <button  @click='group_type=5'>去小儿子家</button>
    </div>
    <son1 v-if="group_type==4" :goodsId='goods_id' @group_type="get_type"></son1>
    <son2 v-if="group_type==5" :type='goodsName' @group_type="get_type"></son2>
  </div>
</template>
<script>
import son1 from './son1';
import son2 from './son2';
    export default{
        data() {
            return {
                group_type:1,
                goods_id:'男鹅,3岁',
                goodsName:'浙东大白鹅',
            }
        },
        //引入子组件
        components: {
            son1,
            son2,
        },
        methods: {
            //子组件返回父组件后执行的函数;
            get_type(i){
              this.group_type = i;
            }
        },

    }
</script>
<style>
    button{
        padding: 10px 15px;
        background: rgb(109, 177, 233);
        color: #fff;
        font-size: 14px;
        border: solid 1px;
        border-radius:6px; 
    }
</style>

子组件son1的内容:

<template>
<div class="son1">
    <span>我是大儿子----{{name}}</span>
    <button @click='_back()'>返回</button>
</div> 
</template>
<script>
    export default{
        name :'son1',
        data() {
            return {
                name:''
            }
        },
        // props用来接收父组件传过来的属性值
        props: {
            goodsId: String  //参数类型可以是String,Number,Boolean,Object, Array ,Function
        },
        created() {
            this.name = this.goodsId;
            console.log(this.$parent); //获取父组件所有的属性方法(不推荐);
        },
        methods: {
            _back(){
            //子组件使用$emit发出自定义事件
                this.$emit("group_type", 1);
            }
        }
    }
</script>

子组件son2的内容:

<template>
<div class="son2">
    <span>我是小儿子----{{name}}</span>
    <button @click='_back()'>返回</button>
</div>

</template>
<script>
    export default{
        name :'son2',
        data() {
            return {
                name:'',
            }
        },
        props: {
            type: String          
        },
        created() {
            this.name = this.type;
        },
        methods: {
            _back(){
               this.$emit("group_type", 1);
            }
        }
    }
</script>

猜你喜欢

转载自blog.csdn.net/call_me_small_pure/article/details/79870238