vue的孙组件获取祖组件数据的方法

项目中遇到一个问题,使用第三方插件的组件库会导致自己封装的组件库无法通过this.$parent.data获取父组件的数据(严格意义上讲这个父组件应该是祖级组件)
在无意尝试中发现使用在孙组件里使用this.$parent.$parent.data即可获取到祖级数据。

<template>
  <div id='detail'>
  	<!-- 第三方框架封装的组件 -->
    <van-popup v-model="showDialog" :show="false" @click-overlay="overPopup">
      <LocationModule></LocationModule><!-- 自己封装的组件 -->
    </van-popup>
  </div>
</template>
//在LocationModule组件中
//如果使用this.$praent.data获取到的数据是第三方框架封装的组件数据,并不是#detail的数据
//此时使用
this.$parent.$parent.data//即可获取到#detail的数据
要在Vue组件获取组件数据,你可以通过以下几种方式实现: 1. 使用 `ref` 引用子组件并直接访问其数据:在组件中,使用 `ref` 属性给子组件命名,然后通过该引用来访问子组件数据。例如: ```html <template> <div> <child-component ref="child"></child-component> <button @click="getChildData">获取组件数据</button> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { getChildData() { const childData = this.$refs.child.childData; console.log(childData); } } } </script> ``` 在上面的示例中,我们通过 `ref` 属性将子组件命名为 "child",然后在 `getChildData` 方法中通过 `this.$refs.child` 来访问子组件实例,并获取其 `childData` 数据。 2. 使用自定义事件:在子组件中,通过 `$emit` 方法触发一个自定义事件,并将数据作为参数传递给组件组件通过监听该自定义事件来获取组件数据。例如: ```html <!-- ChildComponent.vue --> <template> <div> <button @click="sendData">发送数据组件</button> </div> </template> <script> export default { data() { return { childData: '子组件数据' } }, methods: { sendData() { this.$emit('childData', this.childData); } } } </script> ``` ```html <!-- ParentComponent.vue --> <template> <div> <child-component @childData="getChildData"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { getChildData(childData) { console.log(childData); } } } </script> ``` 在上面的示例中,子组件通过 `$emit` 方法触发了一个名为 "childData" 的自定义事件,并将 `childData` 数据作为参数传递给组件组件通过 `@childData` 监听该自定义事件,并在 `getChildData` 方法获取组件传递过来的数据。 这些是获取组件数据的常用方法,你可以根据自己的需求选择合适的方式来实现。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值