Vue: Inherit/Bind all props from parent

Created on 14 Oct 2016  路  5Comments  路  Source: vuejs/vue

Allow child component to auto inherit props from its parent.

<!-- ComponentA.vue -->
<template>
  <div>{{ hello }}</div>
</template>

<script> 
export default {
  props: {
    hello: String,
  },
};
</script>
<!-- ComponentB.vue -->
<template>
  <div>
    <component-a></component-a> World!
    <!-- or -->
    <component-a v-props></component-a> World!
  </div>
</template>

<script> 
import ComponentA from './ComponentA.vue';

export default {
  props: { ...ComponentA.props },
  components: { ComponentA },
};
</script>

Most helpful comment

I like to use a rendered function + functional component:

// ComponentB.js

import ComponentA from './ComponentA.vue';

export default {
  functional: true,
  components: {
    ComponentA
  },
  render (createElement, context) {
    return createElement(ComponentA, {
      props: {
        hello: 'My new Default', // You can even define
        language: 'pr', // default values.
        ...context.props // And then pass the remaining props
      },
      on: context.listeners
    })
  }
}

All 5 comments

Hi, thanks for filling this issue.
Inheriting everything is an anti-pattern, and had been removed from Vue long ago, so please declare the props specifically.

Totally agree with that.

BTW how about something like this?

<template>
   <component-a props="{ title, show, other }"></component-a>
   <!-- instead of -->
   <component-a :title=title :show=show :other=other></component-a>
</template>

You can use v-bind ;)

<component-a v-bind="{ title: title, show: show, other: other }"></component-a>

And if you're sure your target browser supports object literal extensions
It can be simplified to

<component-a v-bind="{ title, show, other }"></component-a>

You can do even better with

<component-a :cprop="computed" v-bind.prop="$props"></component-a>

component-a will receive only its own props even if this.$props contains other props which the child is not interested in, they will be filtered.
By doing so, if you have a computed property, you have to specify the watcher (see cprop)

EDIT this behavior no longer work after v2.2.0-beta.1

I like to use a rendered function + functional component:

// ComponentB.js

import ComponentA from './ComponentA.vue';

export default {
  functional: true,
  components: {
    ComponentA
  },
  render (createElement, context) {
    return createElement(ComponentA, {
      props: {
        hello: 'My new Default', // You can even define
        language: 'pr', // default values.
        ...context.props // And then pass the remaining props
      },
      on: context.listeners
    })
  }
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

bdedardel picture bdedardel  路  3Comments

loki0609 picture loki0609  路  3Comments

hiendv picture hiendv  路  3Comments

finico picture finico  路  3Comments

paceband picture paceband  路  3Comments