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

相关推荐
RadiumAg1 小时前
记一道有趣的面试题
前端·javascript
yangzhi_emo1 小时前
ES6笔记2
开发语言·前端·javascript
yanlele1 小时前
我用爬虫抓取了 25 年 5 月掘金热门面试文章
前端·javascript·面试
中微子3 小时前
React状态管理最佳实践
前端
烛阴3 小时前
void 0 的奥秘:解锁 JavaScript 中 undefined 的正确打开方式
前端·javascript
中微子3 小时前
JavaScript 事件与 React 合成事件完全指南:从入门到精通
前端
Hexene...3 小时前
【前端Vue】如何实现echarts图表根据父元素宽度自适应大小
前端·vue.js·echarts
初遇你时动了情3 小时前
腾讯地图 vue3 使用 封装 地图组件
javascript·vue.js·腾讯地图
dssxyz3 小时前
uniapp打包微信小程序主包过大问题_uniapp 微信小程序时主包太大和vendor.js过大
javascript·微信小程序·uni-app
华子w9089258593 小时前
基于 SpringBoot+VueJS 的农产品研究报告管理系统设计与实现
vue.js·spring boot·后端