Conditional rendering in Vue: Show only if Firestore field value matches a specific string value
P粉007288593
2023-08-28 18:48:23
<p>Firestore database fields (<code>reviewPrivacy</code> fields in the "review" collection) are of type string, populated by Vue form inputs (radio buttons), with three possible answers (values) One is <code>keepFullyPrivate</code>. </p>
<p>If the value of <code>review.reviewPrivacy</code> is <code>keepFullyPrivate</code>, I want to show that <code><h2>the reviewer's identity is private< /h2></code>. </p>
<p>Once this is working, I will add the <code>v-if-else</code> and <code>v-else</code> options to display different content for each option. </p>
<p>My code is as follows. </p>
<p>No errors are flagged in VSC, but the text in the <code><h2></code> tag always appears no matter what the value of <code>review.reviewPrivacy</code> , regardless of whether it is equal to <code>keepFullyPrivate</code>. </p>
<pre class="brush:php;toolbar:false;"><div v-if="('review.reviewPrivacy', '==', 'keepFullyPrivate')"><h2> Commenter's identity is private</h2></div></pre>
<p>Update (additional information): </p>
<ul>
<li>I am using Vue 3.2.1 version</li>
<li>The data obtained from Firestore is correct. For example, in the same parent as the code above, this line of code <code><p>Privacy choices for this review: {{ review.reviewPrivacy }}</p></code> in the DOM Display the following text: <em>Privacy choices for this comment: postAnonPublic</em>, which is a <code>v-else-if</code> condition. </li>
</ul>
<p>Second update: As requested in the comments, make the code a complete block: </p>
<pre class="brush:php;toolbar:false;"><div class="review-detailZ">
<div> <!-- BEGIN main (left-hand) column -->
<p>Privacy choices for this review: {{ review.reviewPrivacy }}</p>
<br />
<!-- Using Vue 3.2.1 version -->
<div v-if="('review.reviewPrivacy', '==', 'keepFullyPrivate')"><h2>The reviewer's identity is private</h2></div>
<div v-else-if="('review.reviewPrivacy', '==', 'postAnonPublic')"><h2>Anonymous - Reviewer: {{ review.userName }}</ h2></div>
<div v-else><h2>Reviewer chose full disclosure - full name {{ review.userFirstName }} {{ review.userLastName }}</h2></div>
<br />
<p>Created {{ review.createdAt }} days ago</p>
<br />
</div></pre>
<p>Thank you! </p>
('review.reviewPrivacy', '==', 'keepFullyPrivate')
is just a set of comma-separated strings, and its value is the last string:'keepFullyPrivate '
, so your tag becomesv-if="'keepFullyPrivate'"
, which is always true. Therefore,div
and itsh2
will always be rendered.The correct expression to compare
review.reviewPrivacy
and'keepFullyPrivate'
is:It is a good practice to use three equal signs (
====
) for strict comparison .Therefore, the final result should be: