Skip to content
Advertisement

Vue js send data from api to new page

I am new to Vue Js and I would like to know how I can send data between two components. I am building a vue app that gets a list of users from an api and displays them. I would like to know I can move data between two components so that I can view more details on a new page.

here is my html code to display the data in a table

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

this is my js code

<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(){

    }
  },
};

where do how I move the data to the view and edit routes/components

Advertisement

Answer

You can use vue-router’s dynamic route matching for this kind of problem. You can simply refactor your /user endpoint to /user/:id and in the component you are calling when landing on /user, you can simply make your api call and fill in the details. You need to update your first router link to have some id in the form of: /user/123 and in the component, you can get that id by calling this.$route.params.id.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement