Add condition to .sync in vue.js

1.3k views Asked by At

I have a component that takes an options property. The options can be synced. As described below.

<component :options.sync="options">...</component>

The component is found in a parent component that has a shouldSync prop. As described below:

<template>
    <div>
        <component :options.sync="options">...</component>
    </div>
</template>
<script>
    export default {
        name: 'parent',
        props: ['shouldSync']
    }
</script>

I want to use .sync modifier only if shouldSync property of the parent component is true. I tried using a dynamic prop with a computed property as below but it didn't work as expected.

<template>
    <div>
        <component :[optionsProp]="options">...</component>
    </div>
</template>
<script>
    export default {
        name: 'parent',
        props: ['shouldSync'],
        computed: {
            optionsProp: () => {
                return this.shouldSync ? 'options.sync' : 'options'
            }
        }
    }
</script>

Unfortunately, it didn't work. Another alternative would be to duplicate the component tag, one with .sync and the other without, and use the v-if directive to determine which one to use. As described below:

<template>
    <div>
        <component v-if="shouldSync" :options.sync="options">...</component>
        <component v-else :options="options">...</component>
    </div>
</template>

But I don't want to do this because the default slot of <component /> contains much code and I don't want to duplicate that. I don't also want to transfer the default slot codes to a new component and include it here.

Is there any better way I can handle this situation? Thanks.

1

There are 1 answers

1
Michal Levý On BEST ANSWER

<component :options.sync="options"> is just syntactic sugar for <component :options="options" @update:options="options = $event">

So just use:

<component  :options="options" @update:options="onUpdateOptions">
methods: {
  onUpdateOptions(newValue) {
    if(this.shouldSync)
      this.options = newValue
  }
}

or...

<component  :options="options" @update:options="options = shouldSync ? $event : options">