LouraQ
LouraQ

Reputation: 6891

How to use toLowerCase() in v-if in vue.js?

In vue.js, I have the following code :

 <q-btn @click="goEditMode" color="primary" icon="edit" label="Edit"
     v-if="this.form.userName.toLowerCase() !== 'admin'" />

It occurs error after I adding toLowerCase().

Here is the error:

[Vue warn]: Error in render: "TypeError: Cannot read property 'toLowerCase' of undefined"

Please help me, thanks!

Upvotes: 2

Views: 1017

Answers (3)

Atul Bansode
Atul Bansode

Reputation: 229

v-if="this.form.userName && this.form.userName.toLowerCase() !== 'admin'" />

You can do this.

Upvotes: 3

Bishan
Bishan

Reputation: 15702

This error occurs due to undefined.toLowerCase().

Looks like you are running toLowerCase on some property that is not present in its parent.

So check if this.form.userName is exists first.

You can perform something like this.

this.form.userName ? this.form.userName.toLowerCase() : ''

Upvotes: 2

wittgenstein
wittgenstein

Reputation: 4462

you have to remove your this. in your template

v-if="form.userName.toLowerCase() !== 'admin'"

demo:

Vue.createApp({
  data() {
    return {
      query: 'oNe'
    }
  }
}).mount('#app')
<script src="https://unpkg.com/vue@next"></script>

<div id="app" class="demo">
  <div v-if="query.toLowerCase() !== 'one'">one</div>
  <div v-if="query.toLowerCase() !== 'two'">two</div>
</div>

demo2:

you can create a computed property to return a condition:

Vue.createApp({
  data() {
    return {
      role: 'aDmIn'
    }
  },
  computed: {
    isAdmin() {
      if (this.role.toLowerCase() === 'admin') {
        return true
      } else {
        return false
      }
    }
  }
}).mount('#app')
<script src="https://unpkg.com/vue@next"></script>

<div id="app" class="demo">
  <div v-if="isAdmin">is admin</div>
  <div v-if="!isAdmin">is user</div>

</div>

Upvotes: 2

Related Questions