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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM