Vue嵌套组件如何传参?

假设有这样两个组件A和B(注意:A、B各自独立,非父子强关系组件,B可灵活替换成其他组件,通过slot传递),A有一个属性hello,B嵌套在A组件中:

<A hello="world">
  <B></B>
</A>
// A.vue
<template>
  <div>
      A: {{hello}}
      <slot></slot>
  </div>
</template>

<script>
export default {
    props: ['hello']
}
</script>

如何在B组件中获取到hello?

<template>
  <div>
      B: {{hello}}
    </div>
</template>

<script>
export default {
    props: ['hello']
}
</script>
阅读 1.7k
2 个回答

A Provide 一个 hello,所有写在 A 里面的组件实例 inject 就可以了(哪个组件需要,哪个 inject 一下就成了。

import { defineComponent, provide, inject } from 'vue';
export default defineComponent({
  name: 'A',
  props: {
    hello: String,
  },
  setup(props) {
    // Provide
    provide('hello', props.hello)
  }
});

export default defineComponent({
  name: 'B',
  setup(props) {
    const hello = inject('hello');
    return {
      hello
    }
  }
});

不知道你用的是 vue2 还是 vue3

vue2:

// B.vue
<template>
  <div>
    {{hello}}
  </div>
</template>
<script>
export default {
   name: 'B',
   props: {
    hello: {
      type: String,
      default: ''
    }
   }
}
</script>

vue3:

// B.vue
<template>
  <div>
    {{hello}}
  </div>
</template>
<script setup lang="ts">
  defineProps<{ hello: string }>()
</script>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题