Bootstrap

『VUE』26. props实现子组件传递数据给父组件(详细图文注释)


欢迎关注 『VUE』 专栏,持续更新中
欢迎关注 『VUE』 专栏,持续更新中

本节内容

父组件传子组件–props
子组件传父组件–自定义事件

本节讲子组件传父组件–通过props里的方法传递,就是父亲写了一个函数,给子组件调用,然后通过这个方法父亲拿到了子组件的数据.


示例代码

<ComponentS title="标题" :onEvent="dataGive" />传递dataGive方法给子组件
子组件中接收方法

  props: {
    title: String,
    onEvent: Function,
  },

子组件中调用方法

  <p>给父组件传的数据:{{ onEvent("我是子组件的数据") }}</p>

父组件中拿到数据

    dataGive(data) {
      console.log("子组件传递给父组件的数据:", data);
      this.message = data;
    },

在这里插入图片描述

ComponentP.vue

<template>
  <h3>组件事件父组件</h3>
  <ComponentS title="标题" :onEvent="dataGive" />
  <div>子组件传递给父组件的数据:{{ message }}</div>
</template>

<script>
import ComponentS from "./ComponentS.vue";

export default {
  data() {
    return {
      message: "",
    };
  },
  components: {
    ComponentS,
  },
  methods: {
    dataGive(data) {
      console.log("子组件传递给父组件的数据:", data);
      this.message = data;
    },
  },
};
</script>

ComponentS.vue

<template>
  <h3>组件事件子组件</h3>
  <p>{{ title }}</p>
  <p>给父组件传的数据:{{ onEvent("我是子组件的数据") }}</p>
</template>

<script>
export default {
  data() {
    return {};
  },
  props: {
    title: String,
    onEvent: Function,
  },
};
</script>


总结

大家喜欢的话,给个👍,点个关注!给大家分享更多计算机专业学生的求学之路!

版权声明:

发现你走远了@mzh原创作品,转载必须标注原文链接

Copyright 2024 mzh

Crated:2024-3-1

欢迎关注 『VUE』 专栏,持续更新中
欢迎关注 『VUE』 专栏,持续更新中
『未完待续』


;