【问题标题】:Laravel backend to Vue not displaying correctly sorted dataVue的Laravel后端未显示正确排序的数据
【发布时间】:2019-07-11 16:54:06
【问题描述】:

简单情况:使用 Laravel 控制器从 DB 中获取所有行并使用 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>

【问题讨论】:

  • 您能否通过手动访问网址来检查您的回复?所以通过浏览器并检查它的顺序
  • 你确定vue中的url应该是readCountry而不是readCountryAll吗?
  • 为什么要评论 //return response()->json($data)// 部分?
  • 如果你 dd($data) 你看它们的顺序是否正确?

标签: php laravel vue.js


【解决方案1】:

这解决了我的问题。

  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);
    }
  }

【讨论】:

    【解决方案2】:

    当通过 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>
    
    

    【讨论】:

    • 我已经尝试过计算属性,但它仍然无法排序。 Laravel 返回集合和数组有什么不同吗?
    • 另外,当我通过 Laravel 控制器对数据进行排序时,它似乎是按 ID 和名称对 Vue 对象进行排序。我觉得 Vue 默认按表 ID 排序。
    猜你喜欢
    • 1970-01-01
    • 2020-07-18
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    相关资源
    最近更新 更多