Vue2——父子之间间的调用
1、父组件给子组件传值使用props
父组件:
<div><SonPage msg="通过props传递值---父=>子" ></SonPage><h1>父组件</h1></div>
子组件
<div :style="{border: '1px solid red'}"><h1>子组件</h1><div>我是父组件传入的参数:{{ msg }}</div>
</div>
<script>
export default {props: {msg: {type: String,}},name: "SonPage",
}
</script>
2、父组件调用子组件方法
父组件
使用 this.$refs.sonRef.子组件方法名。父组件在使用子组件时要加ref,上下一致
<template><div><SonPage ref="sonRef" ></SonPage><h1>父组件</h1><button @click="opSon">我要调用子组件</button></div>
</template><script>
import SonPage from "@/views/SonPage";export default {name: "pPage",components: {SonPage},methods: {opSon() {this.$refs.sonRef.ParentOpSon("我是父组件调用子组件方法传入的参数");},},
}
</script>
子组件
<template><div :style="{border: '1px solid red'}"><h1>子组件</h1><div>这里是父组件调用子组件方法传入的参数:{{ msg2 }}</div></div>
</template><script>
export default {name: "SonPage",data() {return {msg2: ""}},methods: {ParentOpSon(parentMsg) {this.msg2 = parentMsg;},},
}
</script><style scoped></style>
结果:
3、子组件调用父组件方法
父组件
使用子组件标签上加@【子组件的this.$emit中第一个参数名】。方法使用 e就是子组件的参数
<template><div><SonPage @opParent="parentMethod"></SonPage><h1>父组件</h1><div>我是子组件调用父组件方法传入的参数{{ sonMsg }}</div></div>
</template>
<script>
import SonPage from "@/views/SonPage";export default {name: "pPage",components: {SonPage},data() {return {sonMsg: ""}},methods: {parentMethod(e) {console.log(e);this.sonMsg = e;}},}
</script><style scoped></style>
子组件
子组件中使用this.$emit("父组件标签上的@的名"," 调用父组件方法的参数")
<template><div :style="{border: '1px solid red'}"><h1>子组件</h1><button @click="opParent">我要调用父组件的方法</button></div>
</template><script>
export default {name: "SonPage",data() {return {msg2: ""}},methods: {opParent() {this.$emit("opParent", "我是子组件调用父组件方法传入的参数")}},
}
</script><style scoped></style>