欢迎光临
我们一直在努力

Vue 组件通信核心机制:父子组件传值的六种实现方式

01:Vue 组件通信核心机制:父子组件传值的六种实现方式

在现代前端开发中,组件化思想是 Vue 框架的基石。而父子组件之间的数据交互(组件通信)则是构建复杂应用的基础能力。本文将详细探讨 Vue 中父组件向子组件传递数据的六种常见方式,包括 Prop 传递、自定义事件、v-model、Provide/Inject、ref 调用以及 $attrs 透传。

1. Props 传递数据

Props 是父子组件通信最基础也是最主要的方式。父组件通过 props 向子组件发送数据,子组件将其视为自己的属性。

1.1 静态传递

在父组件中,我们可以直接将字符串常量传递给子组件。

<!– 父组件 Parent.vue –>
<template>
<ChildComponent title="静态标题" />
</template>

1.2 动态绑定

使用 v-bind 缩写 :,将父组件的 data 或计算属性动态绑定到子组件的 props 上。

<!– 父组件 Parent.vue –>
<template>
<ChildComponent :title="parentTitle" />
</template>

<script>
export default {
data() {
return {
parentTitle: "动态数据"
}
}
}
</script>

2. 自定义事件 ($emit)

当子组件需要向父组件发送消息或数据时,子组件可以使用 $emit 触发自定义事件,父组件通过 v-on 或 @ 监听该事件。

<!– 子组件 Child.vue –>
<template>
<button @click="handleClick">点击触发事件</button>
</template>

<script>
export default {
methods: {
handleClick() {
this.$emit('custom-event', '从子组件传递的数据');
}
}
}
</script>

<!– 父组件 Parent.vue –>
<template>
<ChildComponent @custom-event="handleData" />
</template>

<script>
export default {
methods: {
handleData(data) {
console.log("接收到的数据:", data);
}
}
}
</script>

3. v-model 语法糖

v-model 是父组件与子组件进行双向数据绑定的常用语法糖。其本质是:子组件内部通过 props 接收 value,并通过 $emit('input') 更新父组件的数据。

3.1 默认用法

<!– 父组件 –>
<template>
<ChildComponent v-model="inputValue" />
</template>

<script>
export default {
data() {
return { inputValue: "" };
}
}
</script>

3.2 自定义 v-model

子组件可以定义自己的 prop 和事件名称。

<!– 子组件 Child.vue –>
<script>
export default {
props: ['currentValue'],
emits: ['update:currentValue'],
methods: {
change(val) {
this.$emit('update:currentValue', val);
}
}
}
</script>

4. Provide/Inject

虽然主要用于跨层级组件通信,但在父子组件间同样适用。父组件通过 provide 提供数据,子组件通过 inject 获取数据,数据响应式跟随变化。

<!– 父组件 Parent.vue –>
<script>
export default {
provide() {
return {
themeColor: "blue",
getUser: () => ({ name: "Admin" })
}
}
}
</script>

<!– 子组件 Child.vue –>
<script>
export default {
inject: ['themeColor', 'getUser']
}
</script>

5. ref 调用方法与变量

通过 ref 标记子组件,父组件可以直接在模板中访问子组件的属性和方法。

<!– 父组件 Parent.vue –>
<template>
<ChildComponent ref="childRef" />
<button @click="callChildMethod">调用子组件方法</button>
</template>

<script>
export default {
methods: {
callChildMethod() {
this.$refs.childRef.childMethod();
console.log(this.$refs.childRef.childData);
}
}
}
</script>

6. $attrs 与 $listeners

这两个属性主要用于组件的属性透传和事件透传(在 Vue 3 Composition API 中主要是 attrs 和 expose 的使用)。

数据流向图

#publish-mermaid-1785340177370-0{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#publish-mermaid-1785340177370-0 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#publish-mermaid-1785340177370-0 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#publish-mermaid-1785340177370-0 .error-icon{fill:#552222;}#publish-mermaid-1785340177370-0 .error-text{fill:#552222;stroke:#552222;}#publish-mermaid-1785340177370-0 .edge-thickness-normal{stroke-width:1px;}#publish-mermaid-1785340177370-0 .edge-thickness-thick{stroke-width:3.5px;}#publish-mermaid-1785340177370-0 .edge-pattern-solid{stroke-dasharray:0;}#publish-mermaid-1785340177370-0 .edge-thickness-invisible{stroke-width:0;fill:none;}#publish-mermaid-1785340177370-0 .edge-pattern-dashed{stroke-dasharray:3;}#publish-mermaid-1785340177370-0 .edge-pattern-dotted{stroke-dasharray:2;}#publish-mermaid-1785340177370-0 .marker{fill:#333333;stroke:#333333;}#publish-mermaid-1785340177370-0 .marker.cross{stroke:#333333;}#publish-mermaid-1785340177370-0 svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#publish-mermaid-1785340177370-0 p{margin:0;}#publish-mermaid-1785340177370-0 .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#publish-mermaid-1785340177370-0 .cluster-label text{fill:#333;}#publish-mermaid-1785340177370-0 .cluster-label span{color:#333;}#publish-mermaid-1785340177370-0 .cluster-label span p{background-color:transparent;}#publish-mermaid-1785340177370-0 .label text,#publish-mermaid-1785340177370-0 span{fill:#333;color:#333;}#publish-mermaid-1785340177370-0 .node rect,#publish-mermaid-1785340177370-0 .node circle,#publish-mermaid-1785340177370-0 .node ellipse,#publish-mermaid-1785340177370-0 .node polygon,#publish-mermaid-1785340177370-0 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1785340177370-0 .rough-node .label text,#publish-mermaid-1785340177370-0 .node .label text,#publish-mermaid-1785340177370-0 .image-shape .label,#publish-mermaid-1785340177370-0 .icon-shape .label{text-anchor:middle;}#publish-mermaid-1785340177370-0 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#publish-mermaid-1785340177370-0 .rough-node .label,#publish-mermaid-1785340177370-0 .node .label,#publish-mermaid-1785340177370-0 .image-shape .label,#publish-mermaid-1785340177370-0 .icon-shape .label{text-align:center;}#publish-mermaid-1785340177370-0 .node.clickable{cursor:pointer;}#publish-mermaid-1785340177370-0 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#publish-mermaid-1785340177370-0 .arrowheadPath{fill:#333333;}#publish-mermaid-1785340177370-0 .edgePath .path{stroke:#333333;stroke-width:1px;}#publish-mermaid-1785340177370-0 .flowchart-link{stroke:#333333;fill:none;}#publish-mermaid-1785340177370-0 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#publish-mermaid-1785340177370-0 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#publish-mermaid-1785340177370-0 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#publish-mermaid-1785340177370-0 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#publish-mermaid-1785340177370-0 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#publish-mermaid-1785340177370-0 .cluster text{fill:#333;}#publish-mermaid-1785340177370-0 .cluster span{color:#333;}#publish-mermaid-1785340177370-0 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#publish-mermaid-1785340177370-0 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#publish-mermaid-1785340177370-0 rect.text{fill:none;stroke-width:0;}#publish-mermaid-1785340177370-0 .icon-shape,#publish-mermaid-1785340177370-0 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#publish-mermaid-1785340177370-0 .icon-shape p,#publish-mermaid-1785340177370-0 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#publish-mermaid-1785340177370-0 .icon-shape .label rect,#publish-mermaid-1785340177370-0 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#publish-mermaid-1785340177370-0 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#publish-mermaid-1785340177370-0 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#publish-mermaid-1785340177370-0 .node .neo-node{stroke:#9370DB;}#publish-mermaid-1785340177370-0 [data-look=\”neo\”].node rect,#publish-mermaid-1785340177370-0 [data-look=\”neo\”].cluster rect,#publish-mermaid-1785340177370-0 [data-look=\”neo\”].node polygon{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1785340177370-0 [data-look=\”neo\”].swimlane.cluster rect{filter:none;}#publish-mermaid-1785340177370-0 [data-look=\”neo\”].node path{stroke:#9370DB;stroke-width:1px;}#publish-mermaid-1785340177370-0 [data-look=\”neo\”].node .outer-path{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1785340177370-0 [data-look=\”neo\”].node .neo-line path{stroke:#9370DB;filter:none;}#publish-mermaid-1785340177370-0 [data-look=\”neo\”].node circle{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1785340177370-0 [data-look=\”neo\”].node circle .state-start{fill:#000000;}#publish-mermaid-1785340177370-0 [data-look=\”neo\”].icon-shape .icon{fill:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1785340177370-0 [data-look=\”neo\”].icon-shape .icon-neo path{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#publish-mermaid-1785340177370-0 :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}子组件 Child父组件 Parent

Props: 静态/动态数据

Provide: 注入数据源

ref: 访问实例方法

Events: $emit 自定义事件

v-model: 双向绑定

Inject: 获取父级数据

$attrs: 接收非 Prop 属性

总结

掌握这六种方式是 Vue 开发者的必修课。Props 适用于单向数据流,$emit 适用于子向父反馈,v-model 适用于双向绑定场景,ref 适用于直接控制子组件内部状态,而 Provide/Inject 则解决了深层嵌套组件的数据共享问题。在实际开发中,根据业务场景选择最合适的方式,是写出高质量代码的关键。

赞(0)
未经允许不得转载:171主机测评 » Vue 组件通信核心机制:父子组件传值的六种实现方式
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址