VueJS 将所有道具传递给子组件

新手上路,请多包涵

我对 VueJS 很陌生。在反应中,您可以轻松地使用休息参数将道具传递给孩子。 Vue中是否有类似的模式?

考虑这个有几个子组件的父组件:

 <template>
<header class="primary-nav">
<search-bar :config="searchBar"><search-bar>
//          ^^^^ this becomes the key on the props for SearchBar
header>
</template>

export default {
  data(){
    return {
      ... a few components ...
      searchBar : {
        model: '',
        name: 'search-bar',
        placeholder: 'Search Away',
        required:true,
        another: true
        andanother: true,
        andonemoreanotherone:true,
        thiscouldbehundredsofprops:true
      }
    }
  }
}

<template>
    <div :class="name">
        <form action="/s" method="post">
            <input type="checkbox">
            <label :for="config.name" class="icon-search">{{config.label}}</label>
            <text-input :config="computedTextInputProps"></text-input>
                        //^^^^ and so on. I don't like this config-dot property structure.
        </form>
    </div>
</template>

  export default {
    props: {
        name: String,
        required: Boolean,
        placeholder: String,
        model: String,
    },
    computed: {
     computedtextInputProps(){
       return justThePropsNeededForTheTextInput
     }
    }
 ...

我不喜欢的是道具是用键 config 或任何其他任意键命名的。文本输入组件(未显示)是一个美化的 input 字段,它可以采用许多属性。我可以在创建组件时展平道具,但这通常是个好主意吗?

我很惊讶这个问题以前没有被问过。

谢谢。

编辑:10-06-2017

相关: https ://github.com/vuejs/vue/issues/4962

原文由 Simon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 433
2 个回答

父组件

<template>
  <div id="app">
    <child-component v-bind="propsToPass"></child-component>
  </div>
</template>

<script>
  import ChildComponent from './components/child-component/child-component'

  export default {
    name: 'app',
    components: {
      ChildComponent
    },
    data () {
      return {
        propsToPass: {
          name: 'John',
          last_name: 'Doe',
          age: '29',
        }
      }
    }
  }
</script>

子组件

<template>
  <div>
    <p>I am {{name}} {{last_name}} and i am {{age}} old</p>
    <another-child v-bind="$props"></another-child> <!-- another child here and we pass all props -->
  </div>
</template>

<script>
  import AnotherChild from "../another-child/another-child";
  export default {
    components: {AnotherChild},
    props: ['name', 'last_name', 'age'],
  }
</script>

上述组件内的另一个子组件

<template>
    <h1>I am saying it again: I am {{name}} {{last_name}} and i am {{age}} old</h1>
</template>

<script>
    export default {
      props: ['name', 'last_name', 'age']
    }
</script>

原文由 Roland 发布,翻译遵循 CC BY-SA 3.0 许可协议

父组件

您可以将任意数量的道具传递给子组件

在此处输入图像描述

子组件

一旦您对所有道具都感到满意,那么您可以在子组件中使用 v-bind="$props" 来检索所有道具。

在此处输入图像描述

最后结果:

在此处输入图像描述

完毕:)

原文由 accimeesterlin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题