Laravel后端到Vue没有显示正确排序的数据

问题描述 投票:1回答:2

简单情况:使用Laravel控制器从DB中获取所有行并使用Vue显示它们。

Laravel从模型中生成正确排序(按名称)的结果,但是当通过Vue获取并循环显示在HTML表格中时,它们将显示为它们存储在数据库中的顺序。

控制器:

public function readCountryAll()
{
    $data = World::Countries()->sortBy('name');
    //return response()->json($data);
    return $data;
}

查看:

    <thead>
            <tr>
                <th>Code</th>
                <th>Name</th>
                <th>Currency</th>
            </tr>
        </thead>
        <tr v-for="country in countryList" :key="country.code">
            <td>{{ country.code }}</td>
            <td>{{ country.full_name }}</td>
            <td>{{ country.currency_code }}</td>
        </tr>
        </table>
 <script>

  export default {

    mounted: function() { 
           this.read();
    },

    data() {
      return {
        countryList: [],
      }
    },
    methods: {

      read() {
        window.axios.get('/readCountry')
            .then(response => this.countryList = response.data)
      },
    },
    components: {

    },
  }
</script>
php laravel vue.js
2个回答
0
投票

当通过JSON命令发送数据时将是随机的。你需要做的是在vuejs中创建一个计算属性,可以称之为“sortedCountryList”并在那里进行排序。然后,您可以在需要输出排序列表的任何位置使用此计算属性。

 <script>

  export default {

    mounted: function() { 
           this.read();
    },

    data() {
      return {
        countryList: [],
      }
    },
    methods: {

      read() {
        window.axios.get('/readCountry')
            .then(response => this.countryList = response.data)
      },
    },
    computed: {
            sortedCountryList: function() {
               return this.countryList.sort(function (a, b) {
                   return b.name - a.name;
               });

            },
    },
    components: {

    },
  }
</script>


0
投票

这解决了我的问题。

  computed: {
    sortedArray: function() {
      function compare(a, b) {
        if (a.name < b.name)
          return -1;
        if (a.name > b.name)
          return 1;
        return 0;
      }

      return this.countryList.sort(compare);
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.