Is there any way to add conditional logic to a string template in Vue.js? This is what I tried however compiling fails.
<div v-for="foo in foos"> {{#if foo.bar === 1}} {{foo.name}} {{/if}} </div>
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.
<div v-for="foo in foos" v-if="foo.bar===1"> {{foo.name}} </div>
Read more about in this documentation.
var demo = new Vue({ el: '#demo', data: { items:[{ id:1, message:'message1' },{ id:2, message:'message2' }] } })
<script src="https://vuejs.org/js/vue.min.js"></script> <div id="demo"> <div v-for="item in items" v-if="item.id==1"> {{item.message}} </div> </div>
Also, you can use a computed
method. See reference here.
var demo = new Vue({ el: '#demo', data: { items:[{ id:1, message:'message1' },{ id:2, message:'message2' }] }, computed: { myMethod: function () { return this.items.filter(function (item) { return item.id === 1 }) } } })
<script src="https://vuejs.org/js/vue.min.js"></script> <div id="demo"> <div v-for="item in myMethod"> {{item.message}} </div> </div>