vue组件爷孙级传值

provide/inject

使用方式

  • 祖先组件里提供 provide
  • 子孙
  • 组件里,inject 相应的名字即可
    // Parent.vue
    
    <template>
      <div class="container">
        <h3>provide/inject 传递方法</h3>
        <div class="description">
          在父组件中通过 provide 向子孙组件提供方法,在子孙组件中通过 inject
          获取父组件提供的方法
        </div>
        <br />
        <Child></Child>
      </div>
    </template>
    
    <script>
    import Child from "./Children";
    
    export default {
      name: "Father",
      components: {
        Child,
      },
      provide() {
        return {
          fatherMethod: this.fatherMethodHandle,
        };
      },
      methods: {
        fatherMethodHandle() {
          console.log("我是父组件的方法");
        },
      },
    };
    </script>
    
    <style scoped lang="scss">
    </style>

    子组件

// Child.vue

<template>
  <div>
    <button @click="childMethod">我是子组件</button>
  </div>
</template>

<script>
export default {
  name: "Child",
  props: {
    msg: String,
  },
  inject: ["fatherMethod"],
  methods: {
    childMethod() {
      console.log("我是子组件的方法,我在子组件中调用了父组件的方法");
      this.fatherMethod();
    },
  },
};
</script>

<style scoped lang="scss">
</style>

一个子组件可以会在多个父组件中使用,当某一个父组件不存在时,此时inject会中的方法会报错,给inject默认值即可

// 转为这种写法
inject: {    
  getTable: { value: "getTable", default: null },   
}

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue中,爷孙组件之间的数据传递是通过props和$emit来实现的。爷孙组件之间不能直接通信,需要通过父组件作为中间组件传递数据。具体实现步骤如下: 1. 在祖父组件(GrandFather.vue)中,定义要传递的数据msg1和msg2,并在模板中将数据传递给父组件(Father)。 2. 在父组件(Father.vue)中,接收来自祖父组件的数据msg1和msg2,并将其作为props传递给子组件(GrandSon)。 3. 在子组件(GrandSon.vue)中,通过props接收来自父组件的数据msg1,并在需要的地方使用。 4. 如果子组件需要向爷爷组件传递数据,则在子组件中通过$emit方法触发一个自定义事件,并将数据作为参数传递给爷爷组件。 5. 在爷爷组件中,通过监听子组件的自定义事件,将接收到的数据绑定到data中的reply属性上,以便在视图层渲染。 通过以上步骤,就可以实现Vue爷孙组件之间的数据传递。请注意,父组件作为中间组件传递数据的过程中需要使用props,而子组件向父组件传递数据需要使用$emit方法。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Vue祖孙组件怎么传值](https://blog.csdn.net/qq_40738077/article/details/106765455)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值