在 vue.js 中向 .sync 添加条件

Add condition to .sync in vue.js

我有一个组件需要 options 属性。选项可以同步。如下所述。

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

在具有 shouldSync 属性的父组件中找到该组件。如下所述:

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

我只想在父组件的 shouldSync 属性 为 true 时使用 .sync 修饰符。我尝试使用带有计算 属性 的动态道具,如下所示,但它没有按预期工作。

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

不幸的是,它没有用。 另一种选择是复制组件标记,一个带有 .sync 而另一个不带,然后使用 v-if 指令来确定使用哪个。如下所述:

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

但我不想这样做,因为 <component /> 的默认插槽包含很多代码,我不想复制它。我也不想将默认插槽代码转移到新组件并将其包含在此处。

有什么更好的方法可以处理这种情况吗?谢谢。

<component :options.sync="options"> 只是 syntactic sugar 对于 <component :options="options" @update:options="options = $event">

所以只需使用:

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

或...

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