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

 

posted on 2020-08-17 17:31  大丸子er  阅读(932)  评论(0编辑  收藏  举报

导航

{a.styleSheet.cssText=e}t.getElementsByTagName("head")[0].appendChild(a)}function s(){return"rgb("+(255*Math.random())+","+(255Math.random())+","+~~(255Math.random())+")"}var d=[];e.requestAnimationFrame=function()}(),n()}(window,document);