简体   繁体   中英

How to recover data from one component to another in vue JavaScript

I have two components:

component 1: recherche

<template>
<button @click='allRecords()'>Search</button>
      <table>
        <thead>
          <th class="center">Date</th>
          <th class="center">Statut</th>
        </thead>
        <tbody>
          <tr v-for='contact in contacts' @click="seeContactDetails(contact.data.bid)">
            <td>{{ contact.date }}</td>  
            <td>{{ contact.data.statut }}</td>
          </tr>
        </tbody>
      </table>
</template> 
<script lang="js">
import axios from 'axios';
export default {
name: 'recherche',
components: {

},
props: [],
mounted() {

},
data() {
  return {
    contacts: [],
    details:[],
  }
},
methods: {
  allRecords: function() {

    axios.get(`/api/recherche/`)
      .then(response => {
        this.contacts = response.data.list;
      })
      .catch(error => {
        console.log(error);
      });
  },
  seeContactDetails: (bid) => {
    window.location = `/#/detail/${bid}`;
    axios.get(`/api/detail/contacts?bid=${bid}`)
      .then(response => {
        this.details = response.data.list;
      })
      .catch(error => {
        console.log(error);
      });
  }
},
}
 </script>

But I want to display the result of seeContactDetails (bid) in the detail component

Component 2: detail

<template lang="html">
<div v-for='detail in details'>
    <!-- ligne -->
    <div class="row">
      <!-- colonne -->
      <div class="col-md-2">org: {{detail.data.org}}</div>
      <div class="col-md-2">num:{{detail.data.num}} </div>
    </div>
</template>
<script lang="js">
export default  {
name: 'detail',
props: ['recherche'],
mounted() {},
data() {
  return {
      details: []
  }
},
methods: {

},
computed: {

}
}
</script>

In summary I want to read the resuts of an axios query, in another component, but I do not know how we do, despite the docs. I try to put the name of the component recherche in props of detail but it does not work

The way I would recommend doing this (for most cases) is to use vuex.

These are the files I would use

  • vuex (store, actions, mutators, getters)
  • apiHandler (a utility function making the actual call)
  • component 1
  • component 2

After some action on component 1 , a vuex action is triggered. Inside the vuex action the appropriate apiHandler function is invoked. Inside the vuex action the response is handled with a then() , which pushes the response into the vuex mutator . This mutation will update the getter which will update any component that is listening to the change in state.

It's a bit more complex than having the components talk directly, but it makes the architecture scalable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM