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

相关推荐
China-quanda12 分钟前
使用 Vite 打包工具库并使用 GitHub Actions 自动化发布npm流程
前端·npm·github
da-peng-song19 分钟前
ArcGIS Desktop使用入门(三)图层右键工具——拓扑(上篇:地图拓扑)
javascript·数据库·arcgis
冷月秋风尚25 分钟前
ES6中迭代器与生成器知识浅析
前端·javascript·es6
blammmp3 小时前
Java : 图书管理系统
java·前端·python
200不是二百3 小时前
Vue-router路由
前端·javascript·vue.js
susu10830189113 小时前
前端vue中如何给reactive赋值
前端·javascript·vue.js
前端学步5 小时前
Vue 3 Composition API 实战技巧:组件间通信与SPA架构
前端·javascript·vue.js
盛夏绽放6 小时前
Vue Router 编程式导航全攻略:深入掌握 push, replace, go, back, forward,beforeEach 方法
前端·vue.js·golang
azhou的代码园6 小时前
基于JAVA+SpringBoot+Vue的医院资源管理系统
java·开发语言·vue.js·spring boot·毕业设计·医院资源管理
小人物.09076 小时前
关于SSR和SSG
前端