• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
御弟哥哥
博客园    首页    新随笔    联系   管理    订阅  订阅
vue组件传参,父子组件以及兄弟组件(非常详细)

一,父子组件传参。

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)
                     })
             }

 

posted on 2021-05-07 16:16  御弟哥哥  阅读(1981)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3