v-select组件disabled属性无法正常更新问题求助
v-select的disabled属性在数组对象场景下无法响应式更新的问题及临时解决方法
问题描述
在使用Vuetify的v-select组件时,遇到了其disabled属性无法随数组对象中的属性变化即时更新的问题。conditions是一个对象数组,每个对象对应一个v-select组件和控制其禁用状态的checkbox,修改checkbox绑定的condition.disableSelection值后,v-select的禁用状态不能即时生效——在changeDisableCondition方法中打印该值显示正确,但只有页面其他内容更新时,v-select才会应用新的禁用状态。
原代码
<template> <v-card class="design-card border-radius-10px" width="25%"> <v-tabs-items v-model="tab"> ... <v-tab-item :value="'tab-2'"> <v-card flat height="10vh"> <v-card-text> <v-checkbox v-model="showConditions" :label="'Show conditions'" hide-details @change="changeShowConditions()" /> </v-card-text> </v-card> <v-card> <div v-for="(condition, i) in conditions" :key="i" class="conditions-container"> ... <v-card-text class="pb-0"> ... <v-row> <v-col cols="7" class="pt-0"> <v-select :ref="`goTo${i}`" v-model="condition.goTo" class="border-radius-10px" :items="allItems" :rules="checkSelfId(condition.selectedCondition._id)" :disabled="condition.disableSelection" :no-data-text="$t('noDataAvailable')" item-text="name" item-value="_id" solo @change="changeGoTo()" > <template v-slot:[`item`]="{ item }"> {{ getNameInLocale(item) }} </template> <template #selection="{ item }"> <div class="ml-1"> <go-to-type :value="item.type" :show-label="false" :show-as-button="true" :button-label="`${getSelectedIndex(item)}.`" /> </div> </template> </v-select> </v-col> <v-col cols="5" class="pt-0"> <v-checkbox v-model="condition.disableSelection" class="text-sm-caption" label="Disable condition selection" hide-details dense @change="changeDisableCondition($event, i)" /> </v-col> </v-row> </v-card-text> </div> </v-card> </v-tab-item> </v-tabs-items> </v-card> </template> <script> export default { name: 'ComponentName', data() { return { ... showConditions: false, conditions: [] } }, methods: { changeShowConditions() { if (showConditions) this.generateInitialConditions() else conditions: [] }, generateInitialConditions() { this.conditions = [ { conditionQuestion: { ...this.selectedCondition[0] }, goTo: 'next' disableSelection: false } ] } } } </script>
尝试过的无效方案
- 尝试配置watcher,但不知道如何针对数组对象场景实现
- 考虑使用computed方法,但无法确定要禁用的具体condition(需要传递索引),不适用
- 通过
goTo${i}的ref手动设置v-select的disabled属性,触发了变更报错 - 添加deep watcher后,属性值打印正确,但v-select的禁用状态依然无法即时更新
临时解决方案
通过在created钩子中预先初始化一个包含所有预期属性的空对象,让数组对象的属性具备Vue响应式特性,从而解决disabled状态不更新的问题:
<script> export default { name: 'ComponentName', data() { return { ... showConditions: false, conditions: [] } }, created() { // 初始化空对象以激活响应式 // 注:这段代码可以抽成方法,此处为示例保留在created中 this.conditions = [ { conditionQuestion: {}, goTo: 'next', disableSelection: false } ] }, methods: { changeShowConditions() { if (showConditions) this.generateInitialConditions() else conditions: [] }, generateInitialConditions() { this.conditions = [ { conditionQuestion: { ...this.selectedCondition[0] }, goTo: 'next' disableSelection: false } ] } } } </script>
内容的提问来源于stack exchange,提问作者VitoCK
相关产品推荐
相关产品推荐

