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触发事件传递值方式适用于子组件向父组件传递数据的场景,可以实现双向数据传递,但需要在父组件中监听子组件的自定义事件,可能会导致代码冗余。
相关推荐
夏幻灵18 分钟前
HTML5里最常用的十大标签
前端·html·html5
冰暮流星19 分钟前
javascript之二重循环练习
开发语言·javascript·数据库
Mr Xu_32 分钟前
Vue 3 中 watch 的使用详解:监听响应式数据变化的利器
前端·javascript·vue.js
未来龙皇小蓝36 分钟前
RBAC前端架构-01:项目初始化
前端·架构
程序员agions44 分钟前
2026年,微前端终于“死“了
前端·状态模式
万岳科技系统开发44 分钟前
食堂采购系统源码库存扣减算法与并发控制实现详解
java·前端·数据库·算法
程序员猫哥_1 小时前
HTML 生成网页工具推荐:从手写代码到 AI 自动生成网页的进化路径
前端·人工智能·html
龙飞051 小时前
Systemd -systemctl - journalctl 速查表:服务管理 + 日志排障
linux·运维·前端·chrome·systemctl·journalctl
我爱加班、、1 小时前
Websocket能携带token过去后端吗
前端·后端·websocket
AAA阿giao1 小时前
从零拆解一个 React + TypeScript 的 TodoList:模块化、数据流与工程实践
前端·react.js·ui·typescript·前端框架