数据传递
父组件 => 子组件
父组件传递
<Child
hobby="唱,跳,RAP"
:age=“age”
/>
子组件接收
props: {
hobby: {
type: String,
default: ''
},
age: {
type: Number,
default: 2.5
}
}
子组件 => 父组件
子组件通过调用父组件的方法,以参数的方式传递到父组件
<Child
:play="play"
/>
play(sth) {
console.log(`今天去${sth}`);
}
方法调用
子组件调用父组件方法
- 通过props将方法传递到子组件
props: {
play: {
type: Function,
default: () => {}
}
}
<div>
<span>{{hobby}}</span>
<button @click="play('RAP')">玩去</button>
</div>
- this.$parent
- this.$emit()
父组件调用子组件方法
- 设置ref
<Child
ref="child"
/>
<button @click="doSth">去玩</button>
doSth() {
this.$refs.child.callMeDo('写作业');
}
- 在子组件创建成功后,将this传递给父组件
父组件
<Child
:onRef="onRef"
/>
<button @click="doSth">去玩</button>
onRef(child) {
this.child = child;
}
子组件
props: {
onRef: {
type: Function,
default: () => {}
}default: () => {}
}
}
created(){
this.onRef(this);
}
总结:
- 父组件的数据和方法都可以通过props的方式传递到子组件,子组件在接收父组件的数据或方法时应进行验证。
- 子组件也可以通过this.$parent得到父组件的,再去获取父组件的数据,调用父组件的方法。
- 父组件可以通过设置ref的方式获取子组件的实例,进而拿到子组件的数据,调用子组件的方法。
- 设置ref还可以在子组件的created()生命周期内,将this通过函数的方式传递给父组件。
相关源代码:
父组件
<template>
<div>
<Child
:onRef="onRef"
:play="play"
hobby="唱,跳,RAP"
ref="child1"
/>
<button @click="doSth">去玩</button>
</div>
</template>
<script>
import Child from './Child'
export default {
name: "Parent",
components: {
Child
},
methods: {
onRef(child) {
this.child2 = child;
},
play(sth) {
console.log(`今天去${sth}`);
},
doSth() {
this.$refs.child1.callMeDo('写作业');
this.child2.callMeDo('吃饭');
}
}
}
</script>
<style lang="less">
</style>
子组件
<template>
<div>
<span>{{hobby}}</span>
<button @click="play('RAP')">玩去</button>
</div>
</template>
<script>
export default {
name: "Child",
props: {
hobby: {
type: String,
default: ''
},
onRef: {
type: Function,
default: () => {}
},
play: {
type: Function,
default: () => {}
}
},
created(){
this.onRef(this);
},
methods: {
callMeDo(sth) {
console.log(`父组件让做的事${sth}`);
}
}
}
</script>
<style lang="less">
</style>