1

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>
1

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Amazing, I didn't know you could combine them like that! Thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.