如何在 vue.js 2 上的输入类型文本中添加运算符三元?
How can I add operator ternary in input type text on vue.js 2?
我的 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>
我想在输入类型文本中添加条件。我像上面的代码一样使用三元运算符
如果代码执行了,是行不通的
没有错误。所以我很困惑解决它
可能我的代码还是不正确
我该如何解决?
问题是您试图在 HTML 中使用 JavaScript 表达式。这行不通。
您可以像这样手动绑定每个属性:
:checked="(expression) ? true : false"
或绑定到计算的 属性,这取决于您的表达式和 returns 您计算的 属性。或者,您可以绑定具有一对多属性的对象,并一次绑定整个对象 (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>
我的 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>
我想在输入类型文本中添加条件。我像上面的代码一样使用三元运算符
如果代码执行了,是行不通的
没有错误。所以我很困惑解决它
可能我的代码还是不正确
我该如何解决?
问题是您试图在 HTML 中使用 JavaScript 表达式。这行不通。
您可以像这样手动绑定每个属性:
:checked="(expression) ? true : false"
或绑定到计算的 属性,这取决于您的表达式和 returns 您计算的 属性。或者,您可以绑定具有一对多属性的对象,并一次绑定整个对象 (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>