1

how-to-mustache-if-else-statement

After I read this, I tried as the article in Vue.js but it emitted just error.

<tr v-for="(data, i) in userList" :key="i">
<td>{{#data.authority==1}}Admin{{/data.authority==1}}</td>
</tr>

If I write just {{data.authority}} then it worked well.

How to use if-else as mustache grammar in Vue.js?

DarkBee
  • 16,592
  • 6
  • 46
  • 58
niddddddfier
  • 397
  • 3
  • 14
  • What error occurred? – DarkBee Nov 10 '21 at 08:59
  • Errors compiling template: `invalid expression: Unexpected identifier in _s(#data.authority==1)+"Admin"+_s(/data.authority==1) Raw expression: {{#data.authority==1}}Admin{{/data.authority==1}}` – niddddddfier Nov 15 '21 at 04:26

2 Answers2

3

Vue uses interpolation with mustache syntax that works different from the post you've shared. Anything you write in {{}} gets evaluated by JavaScript.

So, you can write any kind of expression:

{{ 2 + 2 }} // output will be 4
{{ 'Hell World' }} // output: 'Hello World'

So, in your situation, you can write a ternary operator:

<tr v-for="(data, i) in userList" :key="i">
  <td>{{ data.authority === 1 ? 'Admin' : 'Not Admin' }}</td>
</tr>

If you want to only show a td element when user.authority === 1 you should use v-if or v-show instead.

You can use expressions and not statements inside {{}}. So a plain if/else would not work.

Lucas David Ferrero
  • 1,630
  • 14
  • 40
1

Like vanilla js inside mustache: {{ data.auth ? 'user' : 'guest'}}

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79