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

时间:2019-02-18 10:22:37

标签: php laravel vue.js

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

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

控制器:

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

Vue:

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

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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);
    }
  }