Galivan
Galivan

Reputation: 5328

Vue - conditionally pass down props

I'd like to know if there is a good way to conditionally pass down one or more props to a child component.

If there is sometimes an id set, then I want to pass it down. I can't set id to null because a prop must have a value. I have solved it before by using a "v-if" like this:

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

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

But it's a workaround which looks bad and it becomes a lot of code if the component has many props. And what if you have two props that may be set or not?

Upvotes: 10

Views: 14911

Answers (3)

Ahmed
Ahmed

Reputation: 151

I think the best way to do so is by using v-bind with a logical operator && :

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

note that it will only pass the prop if (id) is available in such case id should not be required as a prop by the component.

Thanks

Upvotes: 4

Nafees Anwar
Nafees Anwar

Reputation: 6598

You can use v-bind and pass it and object containing all your props. and conditionally add your id prop like this.

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

Upvotes: 9

T. Short
T. Short

Reputation: 3614

You can do it using v-bind and dynamically creating the list of props with a method.

Here is an example:

<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>

In the above example, the prop id will only be passed if passId is true.

Upvotes: 8

Related Questions