Working with a <form>
in the context of vue
has been successful as I am able to send the form data to the server, receive a JSON response, and print it on the console.
However, my current challenge involves displaying this JSON response on a different page. For example, I have two separate .vue
files: GetAnimal.vue
, responsible for fetching animal data from an API, and DisplayAnimal.vue
, designed to showcase the retrieved animal's information. The task now is to pass the animal data received by GetAnimal.vue
to DisplayAnimal.vue
.
GetAnimal.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>
response: The JSON response consists of various attributes like:
{
"fur-color": "yellow",
"population": 51000,
"isExtinct": false,
"isDomesticated": true
}
The goal is to transfer this JSON data to DisplayAnimal.vue
located at the /viewanimal
endpoint:
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>
Question arises: How can this be achieved? Although familiar with using this.$router.push({ path });
for navigation purposes, applying it to pass a JSON response is uncharted territory. Is this method considered correct or best practice?
EDIT:
An attempt was made by adding the following data to GetAnimal.vue:
data: function() {
return {
animal: {
name: 'Cat',
furColor: 'red',
population: '10000',
isExtinct: false,
isDomesticated: true
}
Additionally, in DisplayAnimal.vue, the script block was updated to include:
<script>
export default {
props: {
animal: {
name: {
type: String
},
furColor: {
type: String
},
population: String,
isExtinct: String,
isDomesticated: String
}
}
}
</script>
Lastly, a method was introduced in GetAnimal.vue aiming to display the test animal using the display component. Unfortunately, the approach didn't yield results and resulted in a blank page.