英文:
How to use multiple ternary operator with Vue js in a template?
问题
我期待返回三个不同的值,取决于模板中的数据。我知道如何在两个条件下使用它,但有没有办法使用超过两个条件?这会导致语法错误。
<option
{{ change === 1 ? '一次变更' : change === 2 ? '两次变更' : change === 3 ? '三次变更' }}></option>
英文:
I'm expecting to return three, more than two different values depending on data in a template. I know how to use it if two conditions, but is there a way to use more than two conditions ? Gives me a syntaxes error.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
<option
{{ change === 1 ? 'One change' : change === 2 ? 'Two changes' : change === 3 ? 'Three changes'}}</option>
<!-- end snippet -->
答案1
得分: 1
如果我理解您的问题正确的话,请查看以下代码片段:(您可以映射变化的类型并使用计算属性返回它们)
const app = Vue.createApp({
data() {
return {
changes: [1,2,3],
changeTypes: new Map([
[1, 'One change'],
[2, 'Two changes'],
[3, 'Three changes']
])
};
},
computed: {
getChanges() {
return this.changes.map(c => {
return this.changeTypes.get(c)
})
}
}
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<select>
<option v-for="change in getChanges">
{{ change }}
</option>
</select>
</div>
希望这可以帮助您理解代码片段。
英文:
If I understood You correctly, please take a look at following snippet: (You can map types of change and return them with computed property )
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const app = Vue.createApp({
data() {
return {
changes: [1,2,3],
changeTypes: new Map([
[1, 'One change'],
[2, 'Two changes'],
[3, 'Three changes']
])
};
},
computed: {
getChanges() {
return this.changes.map(c => {
return this.changeTypes.get(c)
})
}
}
})
app.mount('#demo')
<!-- language: lang-html -->
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<select>
<option v-for="change in getChanges">
{{ change }}
</option>
</select>
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论