我对 VueJS 很陌生。在 React 中,您可以轻松地使用 rest 参数将 Prop 传递给 child 。 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
}
}
...
我不喜欢的是 props 是用键 config
或任何其他任意键命名的。文本输入组件(未显示)是一个美化的 input
字段,可以采用许多属性。我可以在创建组件时展平 Prop ,但这通常是个好主意吗?
我很惊讶以前没有人问过这个问题。
谢谢。
编辑:10-06-2017
最佳答案
父组件
<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>
关于javascript - VueJS 将所有 Prop 传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44472276/