前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Vue】子组件调用父组件的方法——案例

【Vue】子组件调用父组件的方法——案例

作者头像
陶然同学
发布2023-10-14 10:37:28
1950
发布2023-10-14 10:37:28
举报
文章被收录于专栏:陶然同学博客

好的,以下是一个简单的案例:

父组件 Parent.vue:

代码语言:javascript
复制
<template>
  <div>
    <h2>Parent Component</h2>
    <child-component @text-updated="updateText"/>
    <p>Text from child component: {{ childText }}</p>
  </div>
</template>

<script>
import ChildComponent from './Child.vue';

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      childText: ''
    }
  },
  methods: {
    updateText(text) {
      this.childText = text;
    }
  }
}
</script>

子组件 Child.vue:

代码语言:javascript
复制
<template>
  <div>
    <h2>Child Component</h2>
    <button @click="updateParentText()">Update Parent Text</button>
  </div>
</template>

<script>
export default {
  methods: {
    updateParentText() {
      this.$emit('text-updated', 'Text updated from child component');
    }
  }
}
</script>
代码语言:javascript
复制
在这个案例中,子组件通过调用 $emit 方法向父组件发送一个自定义事件 text-updated,并传递一个字符串参数来更新父组件中的 childText 数据,从而实现子组件调用父组件的方法。在父组件中,我们监听了 text-updated 事件,并将其对应的处理方法 updateText 定义在父组件中,当子组件调用 $emit 方法时,该方法会被自动触发,从而更新父组件中的数据。
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-07-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档