【知识分享】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 组件之间传递数据的常见方法和示例。

相关推荐
朦胧之8 小时前
AI 编程-老项目改造篇
java·前端·后端
swipe11 小时前
从 0 到 1 实现大文件上传:分片、秒传、断点续传、暂停、重试与服务端合并
前端·javascript·面试
爱勇宝11 小时前
我做了一个只用来搜歌词的小 App
android·前端·后端
甲维斯11 小时前
用AI还原《坦克大战》并3D化升级!
前端·人工智能·游戏开发
IT_陈寒12 小时前
SpringBoot自动配置坑了我一晚上,原来问题出在这
前端·人工智能·后端
kyriewen13 小时前
AI 生成的代码能跑就行?这 5 个坑迟早炸
前端·javascript·ai编程
kisshyshy13 小时前
🍦 雪糕、食堂、火车厢:三幅漫画吃透栈、队列与链表
javascript·算法
谷子在生长13 小时前
纯血鸿蒙自定义弹窗最佳实践:从「到处复制」到「一行调用」
前端·harmonyos
壹方秘境13 小时前
我用Go语言开发了一个跨平台的HTTPS抓包和调试工具
前端·后端·ios
神秘面具男13 小时前
HarmonyOS 6.0跨端远程控制
前端·后端