Vue - 有条件地传递道具

  • 本文关键字:有条件 Vue vue.js
  • 更新时间 :
  • 英文 :


我想知道是否有一种好方法可以有条件地将一个或多个 props 传递给子组件。

如果有时有一套id,那么我想把它传下去。我无法将id设置为 null,因为道具必须具有值。我之前已经通过使用这样的"v-if"解决了它:

<survey-wrapper v-if="id" :inputJson="inputJson" :id="id"></survey-wrapper>
<survey-wrapper v-else :inputJson="inputJson"></survey-wrapper>     // <--  no id

但这是一种看起来很糟糕的解决方法,如果组件有很多道具,它会变成很多代码。如果你有两个道具可以设置或不设置怎么办?

您可以使用v-bind并传递它和包含所有道具的对象。 并像这样有条件地添加您的id道具。

<survey-wrapper v-bind="{ inputJson, ...(id ? { id } : {}) }"></survey-wrapper> 

您可以使用v-bind并使用方法动态创建 props 列表来做到这一点。

下面是一个示例:

<template>
<div id="app">
<Component v-bind="propsToPass()"/>
</div>
</template>
<script>
export default {
name: "App",
components: {
Component
},
data() {
return {
passId: true
}
},
methods: {
propsToPass() {
const result = {};
if (this.passId) {
result.id = 1;
}
return result
}
}
};
</script>

在上面的例子中,只有当passIdtrue时,才会传递道具id

我认为最好的方法是将 v-bind 与逻辑运算符 && 一起使用:

<survey-wrapper :inputJson="inputJson" v-bind="id && {id}" />

请注意,只有当 (id( 可用时,它才会传递 prop,在这种情况下,组件不应要求 id 作为 prop。

谢谢

最新更新