【问题标题】:Add condition to .sync in vue.js在 vue.js 中为 .sync 添加条件
【发布时间】:2020-10-17 12:39:27
【问题描述】:

我有一个带有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>

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

有没有更好的方法来处理这种情况?谢谢。

【问题讨论】:

    标签: javascript vue.js synchronization vue-props dynamic-properties


    【解决方案1】:

    &lt;component :options.sync="options"&gt; 只是 syntactic sugar 用于 &lt;component :options="options" @update:options="options = $event"&gt;

    所以只需使用:

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

    或者...

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

    【讨论】:

    • 感谢回复,我试试看。
    猜你喜欢
    • 1970-01-01
    • 2017-08-17
    • 2017-06-12
    • 2019-04-13
    • 2017-08-24
    • 2017-07-07
    • 1970-01-01
    • 2020-11-15
    • 2021-06-13
    相关资源
    最近更新 更多