一、父组件向子组件传值和方法
我们知道,默认情况下,子组件是无法获取到父组件的值和方法的。
子组件想要获取父组件的值,需要父组件给被引用的子组件绑定一个自定义属性来接收父组件传的值
//通过v-bind绑定一个自定义属性,msg是父组件定义的值 Vue.component("parent",{ template:` <div> <h1>父组件</h1> <child :parMsg="msg"></child> </div> ` });
子组件需要用props中接收父组件传递的值,并且props中的参数是只读的
// 子组件可以直接调用props中的参数 Vue.component("child",{ template:` <div> <h1>子组件</h1> <p>{{parMsg}}</p> </div> `, props:["parMsg"] });
子组件获取父组件data的简单方法
直接this.$parent.变量, 比如:this.$parent.name
子组件想要获取父组件的方法,需要父组件给被调用的子组件绑定一个自定义的方法名
// func为自定义的方法名 ,show为父组件的方法 Vue.component("parent",{ template:` <div> <h1>父组件</h1> <child @func="show"></child> </div> `, methods:{ show(){ console.log("我是你爸爸"); } } });
子组件中想要调用父组件的方法,必须通过$emit方法触发, $emit("需要触发的方法","需要传递的参数")
Vue.component("child",{
template:`
<div>
<h1>子组件</h1>
<button @click="myClick">点我</button>
</div>
`,
methods:{
myClick(){
this.$emit("func");
}
}
});
二、子组件向父组件传值
子组件向父组件传值相对麻烦一点,通过给被调用子组件绑定自定义方法的方式,在this.$emit()中传递值,父组件定义一个方法接收
Vue.component("parent",{
template:`
<div>
<h1>父组件</h1>
<child @dataEvent="getData"></child>
<p>{{msgs}}</p>
</div>
`,
data:function(){
return {
msgs:""
}
},
methods:{
getData(msg){
this.msgs = msg;
}
}
});
Vue.component("child",{
template:`
<div>
<h1>子组件</h1>
<button @click="sendData">想获取我的值吗?点我</button>
</div>
`,
data:function(){
return {
msg:"我是大头儿子"
}
},
methods:{
sendData(){
this.$emit("dataEvent",this.msg);
}
}
});
子组件向父组件传值的简单写法
首先,需要给被调用的子组件上添加属性ref,
然后,直接this.$refs.子组件的ref值.变量 比如:this.$refs.mySon.name
Vue.component("parent",{
template:`
<div>
<child ref="mySon"></child>
</div>
`
});
原文:https://www.cnblogs.com/Ryan777/p/10734759.html