如何在Vue.js模板中使用多个三元运算符?

huangapple go评论109阅读模式
英文:

How to use multiple ternary operator with Vue js in a template?

问题

我期待返回三个不同的值,取决于模板中的数据。我知道如何在两个条件下使用它,但有没有办法使用超过两个条件?这会导致语法错误。

  1. <option
  2. {{ 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 -->

  1. &lt;option
  2. {{ change === 1 ? &#39;One change&#39; : change === 2 ? &#39;Two changes&#39; : change === 3 ? &#39;Three changes&#39;}}&lt;/option&gt;

<!-- end snippet -->

答案1

得分: 1

如果我理解您的问题正确的话,请查看以下代码片段:(您可以映射变化的类型并使用计算属性返回它们)

  1. const app = Vue.createApp({
  2. data() {
  3. return {
  4. changes: [1,2,3],
  5. changeTypes: new Map([
  6. [1, 'One change'],
  7. [2, 'Two changes'],
  8. [3, 'Three changes']
  9. ])
  10. };
  11. },
  12. computed: {
  13. getChanges() {
  14. return this.changes.map(c => {
  15. return this.changeTypes.get(c)
  16. })
  17. }
  18. }
  19. })
  20. app.mount('#demo')
  1. <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
  2. <div id="demo">
  3. <select>
  4. <option v-for="change in getChanges">
  5. {{ change }}
  6. </option>
  7. </select>
  8. </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 -->

  1. const app = Vue.createApp({
  2. data() {
  3. return {
  4. changes: [1,2,3],
  5. changeTypes: new Map([
  6. [1, &#39;One change&#39;],
  7. [2, &#39;Two changes&#39;],
  8. [3, &#39;Three changes&#39;]
  9. ])
  10. };
  11. },
  12. computed: {
  13. getChanges() {
  14. return this.changes.map(c =&gt; {
  15. return this.changeTypes.get(c)
  16. })
  17. }
  18. }
  19. })
  20. app.mount(&#39;#demo&#39;)

<!-- language: lang-html -->

  1. &lt;script src=&quot;https://unpkg.com/vue@3/dist/vue.global.prod.js&quot;&gt;&lt;/script&gt;
  2. &lt;div id=&quot;demo&quot;&gt;
  3. &lt;select&gt;
  4. &lt;option v-for=&quot;change in getChanges&quot;&gt;
  5. {{ change }}
  6. &lt;/option&gt;
  7. &lt;/select&gt;
  8. &lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月14日 16:46:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76246597.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定