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触发事件传递值方式适用于子组件向父组件传递数据的场景,可以实现双向数据传递,但需要在父组件中监听子组件的自定义事件,可能会导致代码冗余。
相关推荐
某公司摸鱼前端22 分钟前
uniapp socket 封装 (可拿去直接用)
前端·javascript·websocket·uni-app
要加油哦~24 分钟前
vue | 插件 | 移动文件的插件 —— move-file-cli 插件 的安装与使用
前端·javascript·vue.js
小林学习编程29 分钟前
Springboot + vue + uni-app小程序web端全套家具商场
前端·vue.js·spring boot
柳鲲鹏30 分钟前
WINDOWS最快布署WEB服务器:apache2
服务器·前端·windows
weixin-a153003083162 小时前
【playwright篇】教程(十七)[html元素知识]
java·前端·html
ai小鬼头2 小时前
AIStarter最新版怎么卸载AI项目?一键删除操作指南(附路径设置技巧)
前端·后端·github
wen's2 小时前
React Native 0.79.4 中 [RCTView setColor:] 崩溃问题完整解决方案
javascript·react native·react.js
一只叫煤球的猫3 小时前
普通程序员,从开发到管理岗,为什么我越升职越痛苦?
前端·后端·全栈
vvilkim3 小时前
Electron 自动更新机制详解:实现无缝应用升级
前端·javascript·electron
vvilkim3 小时前
Electron 应用中的内容安全策略 (CSP) 全面指南
前端·javascript·electron