【知识分享】Vue组件之间数据的传递

在 Vue 中,组件之间数据的传递可以通过 props、$emit 和事件总线等方式实现。下面我将为你讲解这些方式,并提供相应的代码示例。

(1)使用 Props 进行父子组件间的数据传递:

父组件可以通过 props 将数据传递给子组件。子组件可以接收父组件传递过来的数据,并在自身内部使用。以下是一个简单的示例:

父组件 Parent.vue:

<template>

<div>

<child :message="parentMessage" />

</div>

</template>

<script>

import Child from './Child.vue';

export default {

components: {

Child

},

data() {

return {

parentMessage: 'Hello from parent'

};

}

};

</script>

子组件 Child.vue:

<template>

<div>

<p>{{ message }}</p>

</div>

</template>

<script>

export default {

props: 'message'

};

</script>

(2)使用 $emit 进行子父组件间的数据传递:

子组件可以通过 $emit 触发自定义事件,并向父组件传递数据。父组件可以监听子组件触发的事件,并获取传递过来的数据。以下是一个简单的示例:

子组件 Child.vue:

<template>

<button @click="sendMessageToParent">Send Message to Parent</button>

</template>

<script>

export default {

methods: {

sendMessageToParent() {

this.$emit('child-message', 'Hello from child');

}

}

};

</script>

父组件 Parent.vue:

<template>

<div>

<child @child-message="handleChildMessage" />

</div>

</template>

<script>

import Child from './Child.vue';

export default {

components: {

Child

},

methods: {

handleChildMessage(message) {

console.log(message); // 输出:Hello from child

}

}

};

</script>

(3)使用事件总线进行非父子组件间的数据传递:

Vue 实例可以作为事件总线,用于在任意两个组件之间进行通信。以下是一个简单的示例:

创建 EventBus.js:

import Vue from 'vue';

export const bus = new Vue();

组件 A:

<template>

<div>

<button @click="sendMessage">Send Message</button>

</div>

</template>

<script>

import { bus } from '@/EventBus.js';

export default {

methods: {

sendMessage() {

bus.$emit('custom-event', 'Hello from component A');

}

}

};

</script>

组件 B:

<template>

<div>

<!-- ... -->

</div>

</template>

<script>

import { bus } from '@/EventBus.js';

export default {

created() {

bus.$on('custom-event', message => {

console.log(message); // 输出:Hello from component A

});

}

};

</script>

这些是在 Vue 组件之间传递数据的常见方法和示例。

相关推荐
web打印社区8 分钟前
Lodop 提示未安装或请升级:Chrome 里先分清该装哪套
开发语言·前端·javascript·chrome·websocket·http
重生之我复员之后重当黄毛10 分钟前
vscode配置c/c++环境
c语言·前端·visual studio
COOLMO研究AI11 分钟前
企业官网服务页的信息架构怎么设计:从用户问题到语义化 HTML
前端·css·html
Alice-YUE21 分钟前
React 渲染机制速通:Render 树、Fiber 树与更新调度
前端·react.js·前端框架·react·fiber·前端性能·渲染机制
FYKJ_201033 分钟前
springboot家政服务平台66766-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·mysql·spark·课程设计
恋猫de小郭41 分钟前
Meta 分享怎么用 AI 迁移 Compose 项目不烧心
android·前端·flutter
Ai-_Man1 小时前
请问豆包的智能体聊天记录该怎么弄
开发语言·前端·javascript·人工智能·小程序·ecmascript·电脑
IT_陈寒1 小时前
SpringBoot自动配置把我坑惨了:这些隐式规则要小心
前端·人工智能·后端
এ慕ོ冬℘゜1 小时前
es6基础知识
前端·javascript·es6
墨鱼老师1 小时前
Go+Gin+Vue 毕设项目:Gin 框架搭建后端基础接口实战
vue.js·golang·go·gin·前后端分离·计算机毕业设计·go 后端