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

Time:01-27

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.

CodePudding user response:

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){
            if (status == 0) return "Deleted"
            if (status == 1) return "Active"
            if (status == 2) return "Completed"
            return "Unknown Status"
        }
    }
});

CodePudding user response:

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