javascript - 在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 中的结果相对应,而无需再次输入日期和数字。啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
解决方案
您已经涉足应用程序状态的问题,并且视图可能会有所不同。推荐的解决方案是 vuex。对于简单的情况,我喜欢将应用程序状态保存在全局 javascript 变量中。您的 vue 组件不需要传递状态,但它们引用了 vue 之外的单一事实来源,它们都可以显示和修改。所以你的应用程序状态是一个联系人数组,而你的 B 组件需要一个更好的名称,它只会将行推送到这个数组上。当您返回 A 时,您的页面将反映新数据。
推荐阅读
- google-chrome - 白名单域的Chrome切换
- java - @ConditionalOnBean(KafkaTemplate.class) 使整个应用程序崩溃
- algorithm - 改变矩阵中的随机位置
- javascript - 注销导致无法对未安装的组件执行 React 状态更新
- ag-grid - Vue 3 模板的文档
- python - 操作系统如何管理虚拟 COM/Serial 端口?
- react-native - 如何使用 Laravel-echo 在博览会上显示通知
- sql - 如何在 xml 文件中获取选择查询的结果
- python - 如何使用 Python 在特定文件夹中创建 csv 文件?
- r - 如何抑制网状stdout和stderr代码块RStudio?