【问题标题】:Vue js send data from api to new pageVue js将数据从api发送到新页面
【发布时间】:2021-09-20 07:35:31
【问题描述】:

我是 Vue Js 的新手,我想知道如何在两个组件之间发送数据。我正在构建一个 vue 应用程序,它从 api 获取用户列表并显示它们。我想知道我可以在两个组件之间移动数据,以便在新页面上查看更多详细信息。

这是我在表格中显示数据的 html 代码

        <table class="table table-hover table-striped">
          <thead>
            <tr>
              <th scope="col">ID</th>
              <th scope="col">Name</th>
              <th scope="col">Occupation</th>
              <th scope="col">Email</th>
              <th scope="col">Bio</th>
              <th scope="col">View</th>
              <th scope="col">Edit</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in users" :key="user.id">
              <th scope="row">{{ user.id }}</th>
              <td>{{ user.name }}</td>
              <td>{{ user.username}}</td>
              <td>{{ user.email }}</td>
              <td>{{ user.phonenumber}}</td>
              <router-link to="/users" class="btn btn-primary">View</router-link>
              </td>
              <td>
                <router-link @click="shareData" :key="user.id" to="/edit" class="btn btn-primary">Edit</router-link>
              </td>
            </tr>
          </tbody>
        </table>

这是我的 js 代码

<script>
import axios from "axios";
import moment from "moment";

export default {
  name: 'Home',
created() {
    this.getUsers();
  },
  data() {
    return {
      users: [],
    };
  },
  methods: {
    getUsers() {
      axios
        .get("https://607e868602a23c0017e8b79e.mockapi.io/api/v1/users")
        .then((response) => {
          console.log(response.data);
          this.users = response.data;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    format_date(value) {
      if (value) {
        return moment(String(value)).format("DD-MM-YYYY");
      }
    },
    shareData(){
    this.$router.push({name:"Users", params:{data:this.users}})
    },
    editData(){

    }
  },
};

我如何将数据移动到视图和编辑路由/组件

【问题讨论】:

    标签: javascript vue.js vue-component vue-router vuejs3


    【解决方案1】:

    如果您想将数据从一个同级组件传递到另一个同级组件(​​具有相同父级的组件),那么您可以使用 Event Bus

    这是我以前学习Event Bus的一篇文章Event Bus Article

    如果您想将数据从父组件传递到子组件,您可以简单地使用 props

    如果您想在代码中的任何位置获取数据,请使用 Vuex

    Vuex 确实非常好用。快乐学习。

    【讨论】:

      【解决方案2】:

      这类问题可以使用vue-router的dynamic route matching。您可以简单地将您的/user 端点重构为/user/:id,并在您登陆/user 时调用的组件中,您可以简单地调用您的api 并填写详细信息。您需要更新您的第一个路由器链接,使其具有以下形式的 id:/user/123,并且在组件中,您可以通过调用 this.$route.params.id 来获取该 id。

      【讨论】:

        【解决方案3】:

        根据您的应用程序的复杂程度,您可以使用VUEX 来存储您所有应用程序的状态,或者如果您有一个小型应用程序并且想花时间学习 VUEX,您可以简单地使用props。使用道具,您可以将对象(数据)传递给您的组件甚至路由。

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-21
        • 2020-11-08
        • 2013-06-26
        • 2019-04-11
        • 1970-01-01
        • 2022-01-15
        • 2020-08-16
        • 1970-01-01
        相关资源
        最近更新 更多