Is there any way to add conditional logic to a string template in Vue.js? This is what I tried however compiling fails.
JavaScript
x
6
1
<div v-for="foo in foos">
2
{{#if foo.bar === 1}}
3
{{foo.name}}
4
{{/if}}
5
</div>
6
Advertisement
Answer
You have to use v-if
directive.
v-if is “real” conditional rendering because it ensures that event listeners and child components inside the conditional block are properly destroyed and re-created during toggles.
JavaScript
1
4
1
<div v-for="foo in foos" v-if="foo.bar===1">
2
{{foo.name}}
3
</div>
4
Read more about in this documentation.
JavaScript
1
12
12
1
var demo = new Vue({
2
el: '#demo',
3
data: {
4
items:[{
5
id:1,
6
message:'message1'
7
},{
8
id:2,
9
message:'message2'
10
}]
11
}
12
})
JavaScript
1
6
1
<script src="https://vuejs.org/js/vue.min.js"></script>
2
<div id="demo">
3
<div v-for="item in items" v-if="item.id==1">
4
{{item.message}}
5
</div>
6
</div>
Also, you can use a computed
method. See reference here.
JavaScript
1
19
19
1
var demo = new Vue({
2
el: '#demo',
3
data: {
4
items:[{
5
id:1,
6
message:'message1'
7
},{
8
id:2,
9
message:'message2'
10
}]
11
},
12
computed: {
13
myMethod: function () {
14
return this.items.filter(function (item) {
15
return item.id === 1
16
})
17
}
18
}
19
})
JavaScript
1
6
1
<script src="https://vuejs.org/js/vue.min.js"></script>
2
<div id="demo">
3
<div v-for="item in myMethod">
4
{{item.message}}
5
</div>
6
</div>