[英]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">
只是<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">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.