簡體   English   中英

當我的Vue.js中的object中存在屬性時,有條件地顯示塊?

[英]Conditionally display blocks when an attribute exists in my object in Vue.js?

我的vue數據object結構如下:

在此處輸入圖像描述

只有當我的表單出現錯誤時, addPersonForm.errors object 才會填充如下:

在此處輸入圖像描述

現在在我的頁面中,當通過執行以下操作填充addPersonForm.errors.name時,我試圖顯示條件錯誤標記和類:

<form action="{{ route('business.queue.add') }}" method="POST" id="manual-add">
    <div class="form-group" v-bind:class="{ 'has-error' : addPersonForm.errors }">
        <label for="add-person-name">Customer Name</label>
        <input type="text" class="form-control" name="name" id="add-person-name" v-model="addPersonForm.fields.name">
        <template v-if="addPersonForm.errors">
            <small class="form-text text-danger">@{{ addPersonForm.errors.name[0] }}</small>
        </template>
        <template v-else>
            <small id="emailHelp" class="form-text text-muted">Name will be displayed internally and to the customer</small>
        </template>

    </div>

加載頁面時,vue 拋出錯誤,指出Cannot read property 'name' of null 我懷疑這是因為addPersonForm.errors在加載時為空。 如果name屬性存在,有人可以幫助我如何正確顯示條件標簽嗎?

(我知道name屬性是一個數組,我只對有錯誤感興趣,如果有則顯示第一個)。

v-if="addPersonForm.errors"應該足以防止錯誤發生。 您確定是這部分代碼觸發了問題嗎?

在任何情況下,您都可以通過使用可選鏈接來確保不會出錯

                                          <!-- note the "?" 👇 -->
<small class="form-text text-danger">@{{ addPersonForm.errors?.name[0] }}</small>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM