Udayanga Amarasinghe
Udayanga Amarasinghe

Reputation: 27

How can I convert integers to corresponding strings in Vue markup?

I have a table for fetching data from the database. I used the "status" field for managing this table.

if the status is = 1, it means "Active" else if the status is = 2, it means "Completed" else if the status is = 0, t means "Deleted".

Then I need to show the above status word in the web page table. I used the below to show the status number.

<tr v-for="(depAcc, index) in depAccs" :key="index">
  <td>{{ index + 1 }}</td>
  <td>{{ depAcc.created_at }}</td>
  <td>{{ depAcc.name }}</td>
  <td>{{ depAcc.status }}</td>

Please instruct me to show the status word on the table.

Upvotes: 1

Views: 99

Answers (2)

Corey B
Corey B

Reputation: 449

In Vue, anything inside double braces {{ //this }} is evaluated as JS. You can therefore write a method to return strings based on your status, then put a function into your double braces.

<tr v-for="(depAcc, index) in depAccs" :key="index">
    <td>{{ index + 1 }}</td>
    <td>{{ depAcc.created_at }}</td>
    <td>{{ depAcc.name }}</td>
    <td>{{ statusText(depAcc.status) }}</td>
</tr>

Then in your page script, add this method

var app = new Vue({
    el: '#app',
    methods:{
        statusText(status){
            let message = "Unknown Status"
            if (status == 0) message = "Deleted"
            if (status == 1) message = "Active"
            if (status == 2) message = "Completed"
            return message
        }
    }
});

Upvotes: 1

isherwood
isherwood

Reputation: 61063

I would create a data property containing the status map, like this:

data() {
  return {
    statusNames: {
      0: 'Deleted',
      1: 'Active',
      2: 'Completed'
    }
  }
}

Then you can reference that in your markup:

<td>{{ statusNames[depAcc.status] }}</td>

Upvotes: 2

Related Questions