Vue页面传值:Props属性与$emit事件的应用介绍

一、vue页面传值

在Vue页面中传值有多种方式,简单介绍以下两种

  1. 通过props属性传递值:父组件在子组件上定义props属性,子组件通过props接收父组件传递的值。
  2. 通过emit触发事件传递值:子组件通过emit方法触发一个自定义事件,并传递需要传递的值给父组件。

二、案例实践

2.1 props属性传递值方式

父组件:

html 复制代码
<template>
  <div>
    <ChildComponent :message="message" />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent,
  },
  data() {
    return {
      message: 'Hello World!'
    };
  },
};
</script>

子组件(ChildComponent.vue):

html 复制代码
<template>
  <div>{{ message }}</div>
</template>

<script>
export default {
  props: {
    message: {
      type: String,
      required: true,
    },
  },
};
</script>
2.2 $emit触发事件传递值

父组件:

html 复制代码
<template>
  <div>
    <ChildComponent @message="handleMessage" />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent,
  },
  methods: {
    handleMessage(message) {
      console.log(message);
    },
  },
};
</script>

子组件(ChildComponent.vue):

html 复制代码
<template>
  <div>
    <button @click="sendMessage">Send Message</button>
  </div>
</template>

<script>
export default {
  methods: {
    sendMessage() {
      this.$emit('message', 'Hello World!');
    },
  },
};
</script>

这两种方式都可以实现在Vue页面间传值,具体使用哪种方式取决于你的需求和组件间的关系。

  • 通过props属性传递值方式适用于父组件向子组件传递数据的场景,可以直接传递数据,简洁方便,但数据传递是单向的。
  • 通过$emit触发事件传递值方式适用于子组件向父组件传递数据的场景,可以实现双向数据传递,但需要在父组件中监听子组件的自定义事件,可能会导致代码冗余。
相关推荐
代码搬运媛7 小时前
Jest 测试框架详解与实现指南
前端
counterxing8 小时前
我把 Codex 里的 Skills 做成了一个 MCP,还支持分享
前端·agent·ai编程
wangqiaowq8 小时前
windows下nginx的安装
linux·服务器·前端
之歆8 小时前
DAY_12JavaScript DOM 完全指南(二):实战与性能篇
开发语言·前端·javascript·ecmascript
发现一只大呆瓜9 小时前
Vite凭什么这么快?3分钟带你彻底搞懂 Vite 热更新的幕后黑手
前端·面试·vite
Maimai108089 小时前
React如何用 @microsoft/fetch-event-source 落地 SSE:比原生 EventSource 更灵活的实时推送方案
前端·javascript·react.js·microsoft·前端框架·reactjs·webassembly
candyTong9 小时前
Claude Code 的 Edit 工具是怎么工作的
javascript·后端·架构
kyriewen10 小时前
产品经理把PRD写成“天书”,我用AI半小时重写了一遍,他当场愣住
前端·ai编程·cursor
humcomm11 小时前
元框架的工作原理详解
前端·前端框架
canonical_entropy11 小时前
Attractor Before Harness: AI 大规模开发的方法论
前端·aigc·ai编程