vue组件之间传值/调用方法的几种方式
(一)父组件向子组件传值==props
1.在父组件中使用子组件的地方绑定数据
<children :message="message"></children
props:{
message:String
}
3.示例:
(二)子组件向父组件传值==$emit,也可以用来调用父组件中的方法
1.子组件直接使用$emit将内部数据传递给父组件
this.$emit("childByValue",this.childValue);
<template>
<child @childByVlaue="childByVlaue"></dhild>
</template>
methods:{
childByValue:function(childValue){
this.name=childValue;
}
}
(三)可以通过$parent和$children获取父子组件参数
$children[i].params
this.$parent.params
1.在state里定义数据和属性
state: {
userName: '',
},
2.在mutation里定义函数
mutations: {
setUserName(state, name) {
state.userName = name
},
},
3.设置值
this.$store.comit('setUserName',params)
this.$store.state.user.userName
(五)父组件调用子组件的方法===ref
1.子组件的方法
methods:{
childMethod(){
alert("我是子组件的方法");
}
}
<template>
<child ref="child"></child>
<div @click="parentMethod"></div>
</template>
methods:{
parentMethod(){
this.$refs.child.childMethod();
}
}
(六)祖孙组件传值provide/inject
父组件:
provide(){
return {
userInfo: this.userInfo
}
}

子孙组件:
inject:["userInfo"],


浙公网安备 33010602011771号