vue组件传参,父子组件以及兄弟组件(非常详细)

2023-03-15,,

一,父子组件传参。

1.首先在项目目录中新建template文件夹,里边包含父组件:List.vue以及子组件:firstComponent.vue,secondComponent.vue。

2.父组件引入子组件并且在components中注册

import LIST from '../template/List';

export default {
     components:{LIST}

}

页面直接引用

<LIST></LIST>

3.父组件向子组件传值

<LIST :pageNum="pageNum" :father="father" :tableData="tableData"></LIST>

子组件需要在props接收

export default{

props:['tableData',"father","pageNum"]

}

子组件页面直接引用

<div>{{father}}</div>

<div>{{pageNum}}</div>

<div :data="tableData"></div>

4.父组件调用子组件的方法需要使用ref定义

<LIST :pageNum="pageNum" :father="father" :tableData="tableData"  ref="myChild"></LIST>

父组件methods方法:

methods: {

clickParent(){
             this.$refs.myChild.childClick();

}
   }

子组件方法:

methods:{

childClick(){
           alert('123')
    }

5.子组件调用父组件的方法使用 this.$emit,或者this.$parent

子组件方法:

methods:{

handleEdit(index, row){
                // this.$parent.handleEdit(index, row);//第一种方法
                this.$emit('handleEdit',index,row);//第二种方法this.$emit

}
  },

父组件需要使用@handleEdit自定义方法名称

<LIST :pageNum="pageNum" :father="father" :tableData="tableData"  ref="myChild"  @handleEdit='handleEdit'></LIST>

父组件方法:

handleEdit(index, row) {

this.idx = index;
            this.form = row;
      },

5.子组件向父组件传值用this.$emit

子组件方法:

sendMsg(){

//func: 是父组件指定的传数据绑定的函数,123:子组件给父组件传递的数据
            this.$emit('func',‘123’)
     }

父组件:@func自定义函数名称

<LIST :pageNum="pageNum" :father="father" :tableData="tableData" ref="myChild" @func="getChild" @handleEdit='handleEdit'></LIST>

methods:{

//接受子组件的传值

getChild(data){
                 console.log(data)
          },

}

二。兄弟组件间的传值使用bus(事件总线)

1.首先新建一个js文件:bus.js:

import Vue from 'vue';

// 使用 Event Bus
          const bus = new Vue();

export default bus;

2.在子组件中分别引入bus.js

import bus from '../bus.js';

(1) firstComponents:第一个子组件中传值:

methods:{

                  sendFirst(){

                      bus.$emit('clickFirstEvent','这是从第一个组件传过来的值')
                   }
            }

(2) secondComponents:第二个子组件中接收:

mounted(){

                   bus.$on('clickFirstEvent',res=>{
                        console.log(res)
                     })
             }

vue组件传参,父子组件以及兄弟组件(非常详细)的相关教程结束。

《vue组件传参,父子组件以及兄弟组件(非常详细).doc》

下载本文的Word格式文档,以方便收藏与打印。