父子组件的传参方式
概述
父子组件、子孙组件传递参数和方法的方式有很多,应根据实际情况选择;
provide/inject
provide 向子孙组件提供父组件的方法或属性;
inject 用于接收祖先组件的方法或属性;
注:通过 provide/inject 注入的属性在子孙组件中无法 watch;
注:通过 provide/inject 注入的对象本身发生变化时,不会传递到子组件,但对象中属性的变化可以传递到子组件,即注入的只是引用;
父组件
export default {
provide() {
return {
fatherMethod: this.fatherMethodHandle,
};
},
methods: {
fatherMethodHandle() {
console.log("我是父组件的方法");
},
},
};
子组件
<script>
export default {
inject: ["fatherMethod"],
};
</script>
$props
通过 props 向子组件传入数据或方法;当嵌套层级很深时不建议使用此方式,因为层层传递会使代码难以维护;
父组件
<template>
<div class="container">
<Child :fatherMethod="fatherMethodHandle"></Child>
</div>
</template>
子组件
export default {
name: "Child",
props: {
fatherMethod: {
type: Function,
require: true,
default: null,
},
},
};
</script>
$parent
在子组件中通过 this.$parent.event
的方式来调用父组件的方法,在嵌套层级很深的子组件中不建议使用该方式。
子组件
<script>
export default {
name: "Child",
methods: {
childMethod() {
console.log(
"我是子组件的方法,我在子组件中通过 $parent 调用了父组件的方法"
);
this.$parent.fatherMethodHandle();
},
},
};
</script>
$emit
在子组件中使用 $emit 向父组件触发一个事件,然后在父组件中监听该事件,在嵌套层级很深的子组件中不建议使用该方式。
子组件
<script>
export default {
name: "Child",
methods: {
childMethod() {
console.log(
"我是子组件的方法,我在子组件中通过 $emit 向父组件触发了事件"
);
this.$emit("call-father");
},
},
};
</script>