Search code examples
vue.jsvuejs2vue-componentvuex

How can I add operator ternary in input type text on vue.js 2?


My vue component like this :

<template>
    <div>
        ...
            <li v-for="category in categories">
                ...
                    <input type="radio" class="category-radio" :value="category.id" (category.id == categoryId) ? 'checked data-waschecked=true' : ''> 
                ...
            </li>
        ...
    </div>
</template>
<script>
    export default {
        props: ['categories', 'categoryId'],
    }
</script>

I want to add condition in input type text. I use operator ternary like above code

If the code executed, it does not work

There is no error. So i'm confused to solve it

Maybe my code is still not correct

How can I solve it?


Solution

  • The issue is you're trying to use JavaScript expression inside plain HTML. This won't work.

    You can either bind each attribute manually like this:

    :checked="(expression) ? true : false" 
    

    or bind to a computed property which depends on your expression and returns your calculated property. Alternatively, you can bind an object with one to many properties, and bind the whole object at once (this is possible also):

    new Vue({
      el: '#app',
      data: {
        categories: [
          { id: 1, name: 'one' },
          { id: 2, name: 'two' },
          { id: 3, name: 'three' }
        ],
        selectedId: 2 // for simplicity
      },
      computed: {
        attrs: function() {
          return function(id) { // computed can also return a function, so you can use args
            return (id === this.selectedId) ? { checked: true, 'data-waschecked': true } : {}
          }
        }
      },
      mounted() { // log your element
        console.log(document.querySelector('input[data-waschecked=true]'))
      }
    });
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    
    <div id="app">
      <ul>
        <li v-for="category in categories">
          <input type="checkbox" v-bind="attrs(category.id)">
        </li>
      </ul>
    </div>