今天和大家分享一下vue父子之间传参以及 父组件调用子组件方法,获取子组件数据;子组件调用父组件方法,获取父组件数据的心得
源码github地址 https://github.com/JustDoIt521/originCoding/tree/master/vue-vuex
Vue版本 3.0 IDE VSCode
新建一个项目,结构如下
父组件 father 子组件firstChild secondChild代码如下
<template>
<div id="father">
<h2>father</h2>
<div style="display:flex;justify-content:space-around;margin-top:80px;">
<first-child></first-child>
<second-child></second-child>
</div>
</div>
</template>
<script>
import firstChild from "@/views/firstChild"
import secondChild from "@/views/secondChild"
export default {
name: "father",
data() {
return {"
}
},
components:{
"first-child": firstChild,
"second-child": secondChild
},
methods: {
}
}
</script>
<template>
<div id="firstChild">
<h3>firstChild</h3>
</div>
</template>
<script>
export default {
name: "firstChild",
data() {
return {
}
},
methods: {
},
}
</script>
<template>
<div id="secondChild">
<h3>secondChild</h3>
</div>
</template>
<script>
export default {
name: "secondChild",
data() {
return {
}
},
methods: {
}
}
</script>
运行项目,页面结构如下
假设说现在父组件问两个子组件,询问说:你们有什么话要给我说呀?(调取子组件方法,获取子组件对自己说的话)
要调取子组件方法,需要使用到ref属性,因此父组件代码变更如下
<template>
<div id="father">
<h2>father</h2>
<div>
<span>{
{msg}}</span>
</div>
<div>
<button @click="getMsg('firstChild')">firstChild</button>
<button @click="getMsg('secondChild')" style="margin-left:10px;">secondChild</button>
</div>
<div style="display:flex;justify-content:space-around;margin-top:80px;">
<first-child ref