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触发事件传递值方式适用于子组件向父组件传递数据的场景,可以实现双向数据传递,但需要在父组件中监听子组件的自定义事件,可能会导致代码冗余。
相关推荐
学习ing小白1 小时前
JavaWeb - 5 - 前端工程化
前端·elementui·vue
一只小阿乐1 小时前
前端web端项目运行的时候没有ip访问地址
vue.js·vue·vue3·web端
计算机学姐2 小时前
基于python+django+vue的旅游网站系统
开发语言·vue.js·python·mysql·django·旅游·web3.py
真的很上进2 小时前
【Git必看系列】—— Git巨好用的神器之git stash篇
java·前端·javascript·数据结构·git·react.js
胖虎哥er2 小时前
Html&Css 基础总结(基础好了才是最能打的)三
前端·css·html
qq_278063712 小时前
css scrollbar-width: none 隐藏默认滚动条
开发语言·前端·javascript
.ccl2 小时前
web开发 之 HTML、CSS、JavaScript、以及JavaScript的高级框架Vue(学习版2)
前端·javascript·vue.js
小徐不会写代码2 小时前
vue 实现tab菜单切换
前端·javascript·vue.js
2301_765347542 小时前
Vue3 Day7-全局组件、指令以及pinia
前端·javascript·vue.js
喝旺仔la2 小时前
VSCode的使用
java·开发语言·javascript