如何在 vue.js 2 的输入类型文本中添加运算符三元?

Suc*_*Man 1 vue.js vue-component vuex vuejs2

我的 vue 组件是这样的:

<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>
Run Code Online (Sandbox Code Playgroud)

我想在输入类型文本中添加条件。我使用运算符三元像上面的代码

如果代码被执行,它不起作用

没有错误。所以我很困惑要解决它

也许我的代码仍然不正确

我该如何解决?

Ego*_*kio 5

问题是您试图在纯 HTML 中使用 JavaScript 表达式。这行不通。

您可以像这样手动绑定每个属性:

:checked="(expression) ? true : false" 
Run Code Online (Sandbox Code Playgroud)

或绑定到一个计算属性,该属性取决于您的表达式并返回您的计算属性。或者,您可以绑定具有一对多属性的对象,并一次绑定整个对象(这也是可能的):

:checked="(expression) ? true : false" 
Run Code Online (Sandbox Code Playgroud)
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]'))
  }
});
Run Code Online (Sandbox Code Playgroud)