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

相关推荐
用泥种荷花11 分钟前
从 0 到 1 做一个支持 NFC 写入的小程序,需要哪些 API?
前端
qq_120840937115 分钟前
Three.js 工程向:Clock、deltaTime 与固定步长主循环
开发语言·javascript·ecmascript
90程序员28 分钟前
纯浏览器解析 APK 信息,不用服务器 | 开源了一个小工具
前端·apk
用户114818678948431 分钟前
Vosk-Browser 实现浏览器离线语音转文字
前端·javascript
江上清风山间明月36 分钟前
Vite现代化的前端构建工具详解
前端·webpack·nodejs·vite
PBitW37 分钟前
apijson 让前端自己定义接口 —— 但不推荐
前端·apijson
存在X37 分钟前
前端自动化编译Jenkins
前端·github
军军君0143 分钟前
数字孪生监控大屏实战模板:云数据中心展示平台
前端·javascript·vue.js·typescript·前端框架·es6·echarts
吴声子夜歌1 小时前
Vue3——使用axios实现Ajax请求
前端·javascript·ajax·axios
qq4356947011 小时前
JavaWeb05
前端·html