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

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

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 -->

&lt;option 
  {{ 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

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

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, &#39;One change&#39;],
        [2, &#39;Two changes&#39;],
        [3, &#39;Three changes&#39;]
      ])
    };
  },
  computed: {
    getChanges() {
      return this.changes.map(c =&gt; {
        return this.changeTypes.get(c)
      })
    }
  }
})
app.mount(&#39;#demo&#39;)

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

&lt;script src=&quot;https://unpkg.com/vue@3/dist/vue.global.prod.js&quot;&gt;&lt;/script&gt;
&lt;div id=&quot;demo&quot;&gt;
  &lt;select&gt;
  &lt;option v-for=&quot;change in getChanges&quot;&gt;
    {{ change }}
  &lt;/option&gt;
  &lt;/select&gt;
&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:

确定