首页 > 其他 > 详细

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

时间:2021-05-07 18:58:09      阅读:28      评论:0      收藏:0      [点我收藏+]

一,父子组件传参。

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组件传参,父子组件以及兄弟组件(非常详细)

原文:https://www.cnblogs.com/qungege/p/14741553.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!