Home > Enterprise >  Why is v-for can't show the value with computed
Why is v-for can't show the value with computed

Time:07-16

This is for select a city and area, It will filter the same data to show it. But I meet with a problem is that when I selected, the value doesn't appear.

I have been try and searched similar code but still doesn't find the solution.

This is the image when of HTML rendering :

enter image description here

Here is template :

<a href="#"  v-for="(live , idx) of filterLivingNames" :key="idx">
    <h3 >{{live.Name}}</h3>
    <p>Address:</p>
    <p>Phone:</p>
</a>

Here is script

import LivingData from '@/assets/LivingData.json';

export default {
    computed: {
        livedata(){
            return LivingData;
        },

        filterLivingNames(){
            let livelength = this.livedata.length

            for(let i = 0 ; i < livelength ; i  ){
                if(this.livedata[i].Region === this.city && this.livedata[i].Town === this.area){
                    console.log(this.livedata[i])
                    return this.livedata[i]
                }
                else{
                    continue
                }
            }
        }
    }
}

Update json file

[
  {
    "Id": "1",
    "Name": "Hotel-1",
    "Region": "Region-1",
    "Town": "Town-1",
  },
  {
    "Id": "2",
    "Name": "Hotel-2",
    "Region": "Region-2",
    "Town": "Town-2",
  },
  {
    "Id": "3",
    "Name": "Hotel-3",
    "Region": "Region-2",
    "Town": "Town-1",
  },
  {
    "Id": "4",
    "Name": "Hotel-4",
    "Region": "Region-1",
    "Town": "Town-2",
  },
]

CodePudding user response:

As you are filtering out the livedata based on Region and Town. You can simply use the Array.filter() method and this will resolve the issue you are facing as it will return the array.

Live Demo :

new Vue({
  el: '#app',
  data: {
    livedata: [
      {
        "Id": "1",
        "Name": "Hotel-1",
        "Region": "Region-1",
        "Town": "Town-1",
      },
      {
        "Id": "2",
        "Name": "Hotel-2",
        "Region": "Region-2",
        "Town": "Town-2",
      },
      {
        "Id": "3",
        "Name": "Hotel-3",
        "Region": "Region-2",
        "Town": "Town-1",
      },
      {
        "Id": "4",
        "Name": "Hotel-4",
        "Region": "Region-1",
        "Town": "Town-2",
      }
    ],
    city: 'Region-1',
    area: 'Town-1'
  },
  computed: {
    filterLivingNames() {
      return this.livedata.filter(obj => obj.Region === this.city && obj.Town === this.area)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <a href="#"  v-for="(livingData, index) of filterLivingNames" :key="index">
    <h3 >{{ livingData.Name }}</h3>
    <p>Address:</p>
    <p>Phone:</p>
  </a>
</div>

  • Related