1.vue父组件给子组件传值的方法
<heador :userName="username"></heador>子组件中通过props接收传值props:{ username:{type:String, default:""
}
}2.vue父组件调用子组件的方法
<heador ref="header"></heador> this.$refs.header.子组件的方法3.子组件传值给父组件
一般通过点击事件this.$emit("getName",this.msg)在这里注册一个事件,把值通过事件带过去。然后在父组件中通过<asidor @getName="getNamefromchild"></asidor>在methods中可以通过getNamefromchild(data){ data就是传过来的值}4.子组件调用父组件的方法
在子组件中<el-button type="primary" @click="diaoyongparent"></el-button>diaoyongparent(){ this.$emit("diaoyongParentfunc") 这里可以带参数}然后在父组件中<asidor @diaoyongParentfunc="diaoyongbychild"></asidor>diaoyongbychild(){ alert("调用父组件的方法了,如果有参数也可以哦") }5.对于非父子组件的传值
首先在main.js里面定义Vue对象的时候在data属性里面创建一个变量,并赋值为一个vue对象,这个变量在整个应用中都可以直接访问,他可以充当EventHub事件中心new Vue({ el:"#app", router, store, components:{App}, data:{Hub:new Vue()
}
})然后在第一个组件里面gotoside(){ this.$root.Hub.$emit("oneEvent",this.msg)}然后在第二个组件里面created(){ this.$root.Hub.$on("oneEvent",function(msg){ alert(msg)})}