I am trying to use a v-if
statement to show some HTML only if the archiveNote
variable is not empty/null.
JavaScript
x
2
1
<div v-if="archiveNote === null || archiveNote ===''" class="form-check ml-3" id="include-note-div">
2
Here is how it’s instantiated
JavaScript
1
7
1
export default {
2
name: "ConfirmReleaseFilesModal",
3
props: {
4
archiveName: String,
5
archiveNote: String
6
},
7
which is then passed in from this other Vue file
JavaScript
1
10
10
1
<confirm-release-files-modal
2
v-if="showConfirmReleaseFilesModal"
3
@cancel="closeModal"
4
@confirmAndEmail="releaseAction"
5
@confirmNoEmail="releaseAction"
6
:archive-name="archiveName"
7
:archive-note ="archiveNote"
8
>
9
</confirm-release-files-modal>
10
The block of HTML still shows when archiveNote
is console.log
out as empty
Advertisement
Answer
If you want to show the <div>
only when it is truthy (not empty/null/etc.), you can simply do:
JavaScript
1
2
1
<div v-if="archiveNote">
2
This gives the same result as the double bang:
JavaScript
1
2
1
<div v-if="!!archiveNote">
2
Both of these expressions evaluate all 8 of JavaScript’s falsy values to false
:
false
null
undefined
- 0
- -0
NaN
''
0n
(BigInt)
and everything else to true
. So if your variable evaluates to anything but these it will be truthy, and the v-if
will show.
Here’s a demo of these and some truthy examples:
JavaScript
1
27
27
1
new Vue({
2
el: "#app",
3
data() {
4
return {
5
falsy: {
6
'null': null,
7
'undefined': undefined,
8
'0': 0,
9
'-0': -0,
10
'''': '',
11
'NaN': NaN,
12
'false': false,
13
'0n': 0n
14
},
15
truthy: {
16
'[]': [],
17
'{}': {},
18
''0'': '0',
19
'1': 1,
20
'-1': -1,
21
'' '': ' ',
22
''false'': 'false',
23
'5': 5
24
}
25
}
26
}
27
});
JavaScript
1
25
25
1
body {
2
background: #20262E;
3
padding: 20px;
4
font-family: Helvetica;
5
}
6
7
#app {
8
background: #fff;
9
border-radius: 4px;
10
padding: 20px;
11
transition: all 0.2s;
12
}
13
#falsy, #truthy {
14
display: inline-block;
15
width: 49%;
16
}
17
.label {
18
display: inline-block;
19
width: 80px;
20
text-align: right;
21
}
22
code {
23
background: #dddddd;
24
margin: 0 3px;
25
}
JavaScript
1
20
20
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
2
<div id="app">
3
<div id="falsy">
4
Falsy:
5
<div v-for="(test, label) in falsy">
6
<div class="label">{{ label }}</div>
7
<code v-if="test">true</code>
8
<code v-else>false</code>
9
</div>
10
</div>
11
12
<div id="truthy">
13
Truthy examples:
14
<div v-for="(test, label) in truthy">
15
<div class="label">{{ label }}</div>
16
<code v-if="test">true</code>
17
<code v-else>false</code>
18
</div>
19
</div>
20
</div>