vue中父傳子,子傳父,兄弟組件傳值方法合集


1.父傳子

//父組件
<father-component :nameData="name"></father-component>
export default{
    data(){
       name'123'
    }
}
//子組件 
<child-component>{{nameData}}</child-component>
export default{
  props:{
    nameData:{
      type:String,
      default:()=>''
    }
  }
}
//父組件-調用子組件的事件
<father-component @click="show"></father-component>
export default{
    methods(){
       show(){
          this.$refs.child.showChild()
       }
    }
}
//子組件 
<child-component ref="child"></child-component>
export default{
  methods:{
        showChild(){
         }
   }
}

 

2.子傳父

//父組件
<father-component " @father="getName"></father-component>
export default{
    method:{
      getName(nameData){
         console.log(nameData)
       }
    }
}
//子組件 
<child-component @cllick="child">{{nameData}}</child-component>
export default{
  data(){
        nameData:'123'
    }
}
method:{
  child(){
     this.$emit('father',nameData)
    }  
}    

3.兄弟組件傳參

在main.js加入
export var Bus = new Vue();

//組件A
<A @click="send"></A>
import {Bus}   from '../main.js'
export default{
    data(){
        news:'1111'
     },
    methods:{
       send(){
           Bus.$emit('buses',this.news)
        }
    }
}
//組件B
<B></B>
import {Bus}   from '../main.js'  
export default{
    data(){
        b:''
     },
    mounted(){
       Bus.$on('buses',function(b)=>{
           this.b = b //b=111
        })
    }
}

 


免責聲明!

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



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