首页 > 解决方案 > 在vue js中从一个组件到另一个组件时如何保留组件的信息

问题描述

如果我有两个组件,第一个称为 A:

<template>
<input  required type='text' v-model.trim="number">
<input type="date" v-model="date" >
<button @click='allRecords(number,date)'>ok</button>
 <table >
    <thead>
      <th>Coordonnées</th>
    </thead>
    <tbody>
      <tr v-for='contact in contacts'>
        <td @click="seeDetails(contact.id)" > {{ contact.data.to }} 
</td> 
      </tr>
    </tbody>
  </table>
</template>

<script lang="js">
import axios from 'axios';
import Vue from 'vue';
export default {
name: 'A',
props: [],
data() {
  return {
contacts: [],
number: '',
date: new Date().toISOString().slice(0,10),
nombre:0
 }

},
methods: {
 allRecords: function(number,date) {
   axios.get(`/api/contacts?number=${number}&date=${date}`)
     .then(response => {
       this.contacts = response.data.list;
       this.nombre = response.data.count;
     })
     .catch(error => {
       console.log(error);
     });
 },
 seeDetails (id) {
     this.$router.push({ name: 'B', params: { id }});
   }, 
}
</script>

第二个称为B:

  <template>
  <div> {{details.data.add }}</div>
  </template>
  <script lang="js">
    import axios from 'axios';
    export default  {
     name: 'B',
     props: [],
      mounted() {
       const id = this.$router.currentRoute.params.id;
    this.fetchContactData(id);
   },
   data() {
    return {
     details: []
    }
  },
  methods: {
   fetchContactData(id){
    axios.get(`/api/recherche/${id}`)
    .then(response => {
        this.details = response.data
    })
    .catch(error => {
        console.log(error);
      });
     },
    },
   } 
  </script>

我希望当我离开我的组件 B 时,我的组件 A 有 A 的信息,该信息与我在 B 中的结果相对应,而无需再次输入日期和数字。啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊

标签: javascriptvue.jsvuex

解决方案


您已经涉足应用程序状态的问题,并且视图可能会有所不同。推荐的解决方案是 vuex。对于简单的情况,我喜欢将应用程序状态保存在全局 javascript 变量中。您的 vue 组件不需要传递状态,但它们引用了 vue 之外的单一事实来源,它们都可以显示和修改。所以你的应用程序状态是一个联系人数组,而你的 B 组件需要一个更好的名称,它只会将行推送到这个数组上。当您返回 A 时,您的页面将反映新数据。


推荐阅读