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触发事件传递值方式适用于子组件向父组件传递数据的场景,可以实现双向数据传递,但需要在父组件中监听子组件的自定义事件,可能会导致代码冗余。
相关推荐
xkxnq4 分钟前
第一阶段:Vue 基础入门(第 13天)
前端·javascript·vue.js
qq_419854056 分钟前
Excel预览
前端
PieroPc15 分钟前
用FastAPI 后端 和 Vue3 前端写一个博客系统 例
前端·vue·fastapi
赵民勇23 分钟前
ES5中prototype和prototype.constructor详解
javascript
xiaoyustudiowww24 分钟前
fetch异步简单版本(Tomcat 9)
java·前端·tomcat
TOPGUS25 分钟前
谷歌Chrome浏览器即将对HTTP网站设卡:突出展示“始终使用安全连接”功能
前端·网络·chrome·http·搜索引擎·seo·数字营销
C_心欲无痕32 分钟前
ts - 模板字面量类型与 `keyof` 的魔法组合:`keyof T & `on${string}`使用
linux·运维·开发语言·前端·ubuntu·typescript
Van_captain33 分钟前
rn_for_openharmony常用组件_Tabs选项卡
javascript·开源·harmonyos
赵民勇35 分钟前
ES6中的const用法详解
javascript·es6
一勺菠萝丶37 分钟前
Java 后端想学 Vue,又想写浏览器插件?
java·前端·vue.js