取值前判断

无论是在HTML中还是在JS中,取值使用前都要进行值是否存在的判断处理。否则容易报Cannot read property 'value' of undefined的错误,如下图所示:
在这里插入图片描述
上图就是在设置访问状态的默认初始值时没有进行值的判断出现的错误。
原代码:

<a-form-item label="访问状态">
    <a-radio-group v-decorator="['accessState',{initialValue: accessState[0].value}]"
                   placeholder="请选择访问状态"
                   :disabled="shows"
    >
        <a-radio v-for="(item, index) in accessState" :value="item.value" :key="index">
            {{item.dictValueName}}
        </a-radio>
    </a-radio-group>
</a-form-item>

正确写法:

<a-form-item label="访问状态">
    <a-radio-group v-decorator="['accessState',{initialValue: accessState.length ? accessState[0].value : undefined }]"
                   placeholder="请选择访问状态"
                   :disabled="shows"
    >
        <a-radio v-for="(item, index) in accessState" :value="item.value" :key="index">
            {{item.dictValueName}}
        </a-radio>
    </a-radio-group>
</a-form-item>

accessState是数组,所以可以先判断其长度,initialValue: accessState.length ? accessState[0].value : undefined

Logo

前往低代码交流专区

更多推荐