首页 > 解决方案 > 使用 axios 和 vuejs 在数据表中获取 json api 数据

问题描述

我有一个数据表,我想根据使用 sequelize 中的 findAll() 返回 json 的 api 传递数据。

但是在 console.log 中,当我调用 getUser 方法时,它会返回带有数据的数据。但是当您将数据插入数据表时:它会通知您它没有数据。

在代码中使用的示例数据表:https ://vuejsexamples.com/a-vue-plugin-that-adds-advanced-features-to-an-html-table/

    <template>
      <div>
        <data-table v-bind="bindings"/>
      </div>
    </template>

    <script>
    import ActionButtons from "../Components/ActionButtons"
    import axios from "axios"

    export default {
      name: 'Usuarios',
      data(){
        return {
          user: this.user,
          errors: []
        }
      },
      computed: {
            bindings() {
                return {
                  data: this.user,
                    lang: "pt-br",
                    actionMode: "single",
                    columns: [
                      {
                        key:"code",
                        title:"Código"
                      },
                      {
                        key:"name",
                        title:"Nome"
                      },
                      {
                        key:"login",
                        title:"Login"
                      },
                      {
                        key:"cpf",
                        title:"CPF"
                      },
                      {
                        key:"actions",
                        title:"Ações",
                        component: ActionButtons,
                      },
                      ],
                }
            }
        },
        methods:{
          getUser() {
                          axios
                            .get("http://localhost:3005/users")
                            .then((res) => {
                              this.user = res.data;
                            })
                            .catch((error) => {
                              console.log(error);
                            });
                    },
                }
    };
    </script>

标签: javascriptvue.jsexpressaxios

解决方案


我相信它不起作用的原因是该getUser()方法已定义但未调用。

如果将异步请求移动到created()生命周期挂钩中,则请求将在组件安装之前发出,因此表应该可以访问数据。https://v3.vuejs.org/api/options-lifecycle-hooks.html#created


推荐阅读