我有一个<form>在vue. 我将该表单发送到服务器,获取 JSON 响应,然后将其打印到控制台。它工作正常。
但是,我需要获取该 JSON 响应并将其显示在另一个页面上。例如,我有两个.vue文件:GetAnimal.vue一个具有表单并从 API 检索动物数据,一个DisplayAnimal.vue显示动物数据。我需要将响应动物数据从 定向GetAnimal.vue到DisplayAnimal.vue。
获取动物.vue:
<template>
<form v-on:submit.prevent="getAnimal()">
<textarea v-model = "animal"
name = "animal" type="animal" id = "animal"
placeholder="Enter your animal here">
</textarea>
<button class = "custom-button dark-button"
type="submit">Get animal</button>
</form>
</template>
<script>
import axios from 'axios';
export default {
name: 'App',
data: function() {
return {
info: '',
animal: ''
}
},
methods: {
getAnimal: function() {
axios
.get('http://localhost:8088/animalsapi?animal=' + this.animal)
.then(response => (this.info = response.data));
console.log(this.info);
}
}
}
</script>
响应:检索带有动物数据的 JSON,如下所示:
{
"fur-color": "yellow",
"population": 51000,
"isExtinct": false,
"isDomesticated": true
}
我现在想将该 JSON 提供给DisplayAnimal.vueat/viewanimal端点:
DisplayAnimal.vue:
<template>
<div>
<p>Animal name: {{animal}}}</p>
<p>Fur color: {{furColor}}</p>
<p>Population: {{population}}</p>
<p>Is extinct: {{isExtinct}}</p>
<p>Is domesticated: {{isDomesticated}}</p>
</div>
</template>
我该怎么做?我知道我可以通过 重定向this.$router.push({ path });,但我只将它用于导航,而这里需要传递 JSON 响应。这甚至是解决此问题的正确/良好做法吗?
编辑:
我试过这个:
在GetAnimal.vue我添加了这些数据:
data: function() {
return {
animal: {
name: 'Cat',
furColor: 'red',
population: '10000',
isExtinct: false,
isDomesticated: true
}
在DisplayAnimal.vue中:
<script>
export default {
props: {
animal: {
name: {
type: String
},
furColor: {
type: String
},
population: String,
isExtinct: String,
isDomesticated: String
}
}
}
</script>
在GetAnimal.vue我添加了这个:
methods: {
animals: function() {
alert("animals");
this.$router.push({name: 'viewanimal',
query: {animal: JSON.stringify(this.animal)}});
},
尝试使用显示组件显示该测试动物。但是它只是没有用 - 我得到一个空页面。

