Vue use route params for axios get request - javascript

So I'm building my first vue project and I've been trying to pass route parameters to an axios get request and it's not working.
this is the code for the page, it gets rendered after the user clicks on a dynamic link in a table of tests
<template>
<v-app>
<app-navbar />
<v-main>
<h3>test {{$route.params.name}}, {{$route.query.status}},{{$route.query.tag}}</h3>
<h3>{{items}}</h3>
</v-main>
</v-app>
</template>
<script>
import appNavbar from '../../../components/appNavbar.vue';
import axios from "axios";
export default {
components : {appNavbar},
name: "App",
data() {
return {
items: [],
};
},
async created() {
try {
const res = await axios.get(`http://localhost:3004/tests`,{ params: $route.params.name });
this.items = res.data;
} catch (error) {
console.log(error);
}
},
};
</script>
<style lang="scss" scoped>
</style>
how can i pass the route params to the axios get function ?

This should be this.$route.params.name inside the script.
const res = await axios.get(`http://localhost:3004/tests`,{ params: this.$route.params.name });

Router.js const routes = [ { path: 'path/:name', name: 'Name', component: ComponentName, } ]

I used #Nitheesh solution I just had to specify the parameter name and it worked perfectly
Solution:
const res = await axios.get(`http://localhost:3004/tests`,{ params: {name:this.$route.params.name} });

Related

I cant get individual documents from a database using id?

I've been using Vue with a firebase database for my data I think where I'm going wrong is with the routing but I'm not 100% sure. what I've done so far is I've got a database with peoples profiles in it and I've use v-for to display all of these profiles out on the home page and now I'm trying to get it so that when you click on their individual profile you got to another page which will then fill the profile out according to a template using the id of the profile you've just clicked to fill in the page with that documents data.
What I know isn't happening is it isn't getting an id of a document because it should console log but it doesn't and it just displays the error message I made that it can't find the profile, as I said I'm pretty sure it is something that has to be done to the router, but I am not sure what to do and how to do it?
Here is the code below of the home page where you first see the profiles and select them.
<script>
import getPremium from "../Composables/getPremium.js";
import getStandard from "../Composables/getStandard.js";
import getBasic from "../Composables/getBasic.js";
const counter = useCounterStore();
const profile = useProfileStore();
const profileA = profilesbasic();
const {Premium, error, load} = getPremium();
load();
const {Standard, error2, load2} = getStandard();
load2();
const {Basic, error3, load3} = getBasic();
load3();
</script>
<template>
<div v-for =" Basics in Basic" :key="Basics.id" >
<router-link to="/Samplebasic">
<div class= "hover:scale-105 transition ease-in-out duration-300 bg-neutral-800 hover:bg-neutral-900 active:bg-neutral-900 text-neutral-400 font-bold rounded-xl">
<br>
<p>{{ Basics.name }}</p>
<img src="../assets/Sample pic.png" class="object-contain ml-6 w-60 h-80 transition ease-in-out duration-300">
<div class="grid grid-cols-2 grid-rows-fit text-left ml-6">
<p>Age:</p>
<p>{{ Basics.Age }}</p>
<p>Location:</p>
<p>{{ Basics.Location }}</p>
<p>Phone:</p>
<p>{{ Basics.Phone }}</p>
</div><br>
</div>
</router-link>
</div>
</template>
This is the JavaScript file that gets the documents from the database and is then imported to the home page.
import { projectFirestore } from "../Firebase/Config";
import { ref } from "vue"
const getBasic = () => {
const Basic = ref([])
const error3 = ref(null)
const load3 = async () => {
try{
const res = await projectFirestore.collection('Basic').get()
Basic.value = res.docs.map(doc => {
console.log(doc.data())
return {...doc.data(), id: doc.id}
})
}
catch (err){
error3.value = err.message
console.log(error3.value)
}
}
return { Basic, error3, load3}
}
export default getBasic
This is the profile page which I'm trying to get filled with the individuals' details depending on the profile you clicked on.
import getPBasic from "../Composables/getPBasic";
const {PBasic, error, load} = getPBasic();
load();
export default {
name: "Slider",
mounted(){
this.PBasic = PBasic;
this.error = error;
this.load = load;
},
data() {
return {
error: {},
PBasic: {},
load: {},
images: [
"/src/assets/sample-1.jpg",
"/src/assets/sample-2.jpg",
"/src/assets/sample-3.jpg",
"/src/assets/sample-4.jpg"
],
currentIndex: 0
};
},
methods: {
next: function() {
this.currentIndex += 1;
},
prev: function() {
this.currentIndex -= 1;
}
},
computed: {
currentImg: function() {
return this.images[Math.abs(this.currentIndex) % this.images.length];
}
}
};
</script>
<template>
<div v-if="error">{{ error }}</div>
<div v-if="PBasic" class="PBasic">
<br><br>
<p class="text-5xl text-red-700 font-serif">{{ PBasic.name }}</p><br><br>
<p>{{ Pbasic.age }}</p>
</template>
This is the javascript file that should get me that individual document based on the id of profile user clicked on.
import { projectFirestore } from "../Firebase/Config";
import { ref } from "vue"
const getPBasic = (id) => {
const PBasic = ref(null)
const error = ref(null)
const load = async () => {
try{
let res = await projectFirestore.collection('Basic').doc(id).get()
if(!res.exists) {
throw Error('That Profile no longer exists')
}
PBasic.value = {...res.data(), id: res.id}
console.log(PBasic.value)
}
catch (err){
error.value = err.message
console.log(error.value)
}
}
return { PBasic, error, load}
}
export default getPBasic
And this is the router of the sample basic as I have it now, I'm pretty sure it's the problem I just don't know how to fix it or what to do to the other files once I've done it?
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../components/Home.vue'
import Login from '../components/Login.vue'
import Advertise from '../components/Advertise.vue'
import Samplebasic from '../components/Samplebasic.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/Login',
name: 'Login',
component: Login,
},
{
path: '/Advertise',
name: 'Advertise',
component: Advertise,
}
{
path: '/Samplebasic',
name: 'Samplebasic',
component: Samplebasic,
}
]
const router = createRouter({
history: createWebHistory(),
routes,
})
export default router;
```
I hope I didn't go on for too long but that's the problem I'm having, and I don't know how to go about any help would be greatly appreciated, Thanks.

vuejs both components get prop from App.js, but one component lost prop data

When I refresh my browser few times when I am on "ActorDetails.vue" page/component, not often but sometimes, I lost my actorsData prop data(should have array of 5 objects but become empty array), at first, I thought it's an API's problem but when I try to console.log() the data inside of "App.js", the data exist... I can't seem to find where the problem is.(Also I did try refresh the browser few times when I am on "ActorsList.vue" page/component, the prop data always exist)
Both pages/components("ActorList.vue" and "ActorDetails.vue") gets topActors data from "App.vue".
(Comments in code)
App.vue
<template>
<div id="app">
<router-view name="homePage" />
<router-view :actorsData="topActors" /> <== "ActorList.vue" and "ActorDetails.vue" use this "router-view"
<div class="over-limit-resolution">Over 4k</div>
</div>
</template>
<script>
import { getActors } from "./util/TheMoveDatabase";
export default {
name: "App",
data() {
return {
topActors: [],
};
},
created() {
getActors.then((result) => {
console.log(result); <== Data always came back from API even when my "actorsData" prop inside of "ActorsDetails.vue" lost it's data.
this.topActors = result;
});
},
methods: {},
};
</script>
ActorsList.vue
<template>
<div class="actors-list">
<router-link to="/">Home</router-link>
<div class="actors-list-container" v-if="allFiveActors">
<div
class="actor-container"
v-for="actorData in actorsData"
:key="actorData.id"
>
<router-link :to="'/actorslist/' + actorData.id">
<h3>{{ actorData.name }} | {{ actorData.id }}</h3>
</router-link>
</div>
</div>
</div>
</template>
<script>
export default {
name: "ActorsList",
props: ["actorsData"],
data() {
return {};
},
computed: {
allFiveActors() {
return this.actorsData.length > 0;
},
},
created() {
console.log(this.actorsData); <== Also tried to refresh the browser when I am on this page/component, prop data always exist.
},
};
ActorsDetails.vue (Page/Component that lost prop data)
<template>
<div class="actor-details">
<router-link to="/actorslist">Actors List</router-link>
<h1>Details page</h1>
<div class="actor-details-container" v-if="actorDetails">
<div class="actor-detail-info">
<h3>{{ actorDetails.name }}</h3>
<p>Birthday: {{ actorDetails.birthday }}</p>
</div>
</div>
</div>
</template>
<script>
import { getActorDetails } from "../util/TheMoveDatabase";
export default {
name: "ActorDetails",
props: ["actorsData", "actorId"],
data() {
return {
actorDetails: {},
};
},
methods: {
checkCurrentActorExist() {
const currentActor = this.getCurrentActor;
// console.log(currentActor);
if (!currentActor) {
// this.$router.push("/");
console.log("does not exist");
}
},
getActor() {
const currentActor = this.getCurrentActor;
console.log(currentActor);
console.log("RAN");
if (currentActor) {
getActorDetails(this.actorId).then((result) => {
this.actorDetails = result;
console.log(this.actorDetails);
});
}
},
},
created() {
this.checkCurrentActorExist();
this.getActor();
console.log(this.actorsData); <== When I am on this page/component and refresh the browser few times, sometimes my "actorsData" prop data is lost.
console.log(this.actorId);
},
computed: {
getCurrentActor() {
return this.actorsData.find(
(actor) => actor.id === parseInt(this.actorId)
);
},
},
};
</script>
Routes.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue';
Vue.use(VueRouter);
const routes = [
{
path: '/',
name: 'Home',
components: {
homePage: Home,
},
},
{
path: '/actorslist',
name: 'ActorsList',
component: () => import('../views/ActorsList.vue'),
},
{
path: '/actorslist/:actorId',
name: 'ActorDetails',
component: () => import('../views/ActorDetails.vue'),
props(route) {
// console.log(route);
return {
actorId: route.params.actorId,
};
},
},
];
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
});
export default router;
Just a guess, but maybe your loading-method sometimes takes to much time and the empty array already has been passed to the component.
I would try to clear the array and re-fill it with the loaded data instead of creating a new array (I would try to empty it using splice or pop and then refill it with push)

How to make nested routing in Vuejs?

HelloWorld.vue
import axios from "axios";
export const router = () => axios.get("https://fakestoreapi.com/products");
<template>
<div>
<div v-for="item in items" :key="item.id">
<b> id: {{ item.id }}</b>
<router-link
:to="`/${item.id}`"
>
{{ item.title }}
</router-link>
</div><!-- end v-for -->
<router-view></router-view>
</div>
</template>
<script>
import { router } from "./router";
export default {
name: "HelloWorld",
components: {},
data() {
return {
items: [],
};
},
mounted() {
router().then((r) => {
this.items = r.data;
});
},
};
</script>
User.vue
import axios from "axios";
export const routerid = (itemId) =>
axios.get("https://fakestoreapi.com/products/" + itemId);
<template>
<div>
<div v-if="item">
<h1>Price: {{ item.price }}</h1>
</div>
<tabs />
</div>
</template>
<script>
import { routerid } from "./routerid";
import tabs from "./tabs";
export default {
name: "User",
components: {
tabs,
},
data() {
return {
item: null,
};
},
mounted() {
this.loadData();
},
computed: {
routeId() {
return this.$route.params.id;
},
},
watch: {
routeId() {
console.log("Reload (route change)");
this.loadData();
}, //reload when route id changes
},
methods: {
loadData() {
console.log("Reloading, ID", this.routeId);
if (!this.routeId) return; // no ID, leave early
routerid(this.$route.params.id).then((item) => {
this.item = item.data;
});
},
},
};
</script>
tabs.vue
import axios from "axios";
export const tabsandcontent = async (itemId) =>
await axios.get("https://fakestoreapi.com/products?limit=" + itemId);
<template>
<div>
<div v-if="item">
<h1>description: {{ item.description }}</h1>
</div>
</div>
</template>
<script>
import { tabsandcontent } from "./tabsandcontent";
export default {
name: "User",
components: {},
data() {
return {
item: null,
};
},
mounted() {
this.loadData();
},
computed: {
tabsandcontent() {
return this.$route.params.id;
},
},
watch: {
tabsandcontent() {
console.log("Reload (route change)");
this.loadData();
}, //reload when route id changes
},
methods: {
loadData() {
console.log("Reloading, ID", this.tabsandcontent);
if (!this.tabsandcontent) return; // no ID, leave early
tabsandcontent(this.$route.params.id).then((item) => {
this.item = item.data;
});
},
},
};
</script>
main.js
import Vue from "vue";
import App from "./App.vue";
import VueRouter from "vue-router";
import HelloWorld from "./components/HelloWorld";
import User from "./components/User";
Vue.use(VueRouter);
const router = new VueRouter({
routes: [
{
path: "/HelloWorld",
name: "HelloWorld",
component: HelloWorld,
children: [{ path: ":id", name: "User", component: User }]
}
]
});
Vue.config.productionTip = false;
new Vue({
router,
render: (h) => h(App)
}).$mount("#app");
code:- https://codesandbox.io/s/combined-logic-api-forked-41lh0f?file=/src/main.js
can you please answer this, In main.js routing I changed from path: "/" to path: "/HelloWorld" then all of sudden output not reflecting... because in my project path:'/' indicates login page??? In this scenario what changes, i need to make, to make logic work
also where is the relation between path:'/' and api call??
You have same name for the variables in tabs component (In watch and computed). And In tabsandcontent.js, you have missed to fetch description for the specific item as performed in routerId.js.
Have a look at modified version which is working as you expected.
https://codesandbox.io/embed/combined-logic-api-forked-ji5oh4?fontsize=14&hidenavigation=1&theme=dark
First thing first, I want you to know that I don't understand what are you asking for. But I'm going to try to answer.
Your first question:
In main.js routing I changed from path: "/" to path: "/HelloWorld" then all of sudden output not reflecting.
Yes, you will not see your HelloWorld.vue component. You can see your page however if you type <your-url>/HelloWorld. Usually the / path is used for something like "Home" page.
However, I've tried checking out your codesandbox. And take a look at your HelloWorld.vue component.
I think you are confused because when you changed the path from / to /HelloWorld apart from the HelloWorld.vue not showing up. It somehow broken the link which causes the API in tabs.vue not functioning.
If that's the case, you just have to simply add HelloWorld/${item.id} in tabs.vue,
<template>
<div>
<div v-for="item in items" :key="item.id">
<b> id: {{ item.id }}</b>
<router-link
:to="`HelloWorld/${item.id}`" // --> Notice this line
>
{{ item.title }}
</router-link>
</div><!-- end v-for -->
<router-view></router-view>
</div>
</template>
This however, isn't a common thing to do routing. You should add your App URLs to main.js. Which also isn't common, but I'm assuming this is just a little reproduction code you made for StackOverflow.
Here are my CodeSandbox edits.
https://codesandbox.io/s/combined-logic-api-forked-jttt8p
I will update the answer again later, I'm still not on my personal laptop.

Gender information disappears when the page is refreshed

Variable named jso disappears when the page is refreshed. Also, is there any other way to send store information than method?
It will work when the page is refreshed and reopened without using a button.
view/userProfile.vue
<template>
<div>
<v-list>
<v-list-item>
{{userdata['username']}}</v-list-item>
<v-list-item> {{userdata['id']}}</v-list-item>
<v-list-item> {{userdata['email']}}</v-list-item>
<v-list-item> {{userdata['phone_number']}}</v-list-item>
<v-list-item> {{userdata['first_name']}} {{userdata['last_name']}}</v-list-item>
<v-list-item > {{userdata['gender']}}</v-list-item>
{{userdata['educational_status']}}
</v-list>
<hr>
{{this.profileData.gender}}
{{jso}} --> variable that disappears on page refresh
</div>
</template>
<script>
Only jso disappears on refresh page:
import Vuetify from "vuetify"
import {UserData} from "../../store/userModule";
import {JsonChoiceData} from "../../store/choiceStore";
import jsonDict from "../../jsonFiles/data.json"
import JsonFile from "../../jsonFiles/jsonfile"
export default {
name: "userProfile",
data(){
return {
profileData:{
username:'',
first_name:'',
last_name: '',
email:'',
phone_number:'',
birthday:'',
gender:'',
educational_status:'',
martial_status:'',
},
}
},
created(){
this.$store.dispatch('initUserData')
this.$store.dispatch('inijson')
},
computed:{
jso(){
return this.$store.getters.user
},
userdata (){
for(var i in this.$store.getters.getUser){
return this.$store.getters.getUser[i]
}
return this.$store.getters.getUser},
},
methods:{
getjsondata(){
console.log(this.userdata['gender'] + "methods")
this.$store.dispatch('getJsonData',this.userdata['gender'])
console.log(this.userdata['gender'])
}
},
mounted(){
this.getjsondata()
}
}
</script>
<style scoped>
</style>
store
import JsonFiles from '../jsonFiles/jsonfile'
import Jsondict from '../jsonFiles/data.json'
import jsonfile from "../jsonFiles/jsonfile";
export const JsonChoiceData = {
state: {
user: [],
},
getters: {
user(state) {
return state.user
},
},
mutations: {
inijson(state, user) {
state.user = user
},
getsonData: function (state, userinput) {
var getJsoncleandata = jsonfile.JsonData(userinput, Jsondict.Gender)
state.user = getJsoncleandata
return getJsoncleandata
}
},
actions: {
inijson(context){
context.commit('inijson', this.getsonData)
},
getJsonData(context,userinput){
context.commit('getsonData',userinput)
}
}
}
getsonData is a mutation and shouldn't be used as payload of another mutation. You are also trying to dispatch initUserData action which is not inside your store. I think that you can try to commit getsonData mutation inside your inijson action.
mutations: {
...,
getsonData: function(state, userinput) {
const getJsoncleandata = jsonfile.JsonData(userinput, Jsondict.Gender);
state.user = getJsoncleandata;
}
...
},
actions: {
inijson(context) {
context.commit('getsonData', null)
},
...
}
Then inside created hook of your component dispach only inijson action:
...
created() {
this.$store.dispatch('inijson')
},
...
If you see strange date make sure that jsonfile.JsonData(userinput, Jsondict.Gender) doesn't return a Promise.
Instead of using global $store you can also consider to use vuex store mappers. component binding helpers

Vue: display response from form submit on another page

I have a <form> in vue. I send that form to server, get a JSON response, print it to console. It works fine.
However I need to take that JSON response and display it on another page. For instance, I have two .vue files: GetAnimal.vue that has the form and retrieves the animal data from an API and a DisplayAnimal.vue that displays animal's data. I need to direct the response animal data from 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:
retrieves a JSON with animal data, say like this:
{
"fur-color": "yellow",
"population": 51000,
"isExtinct": false,
"isDomesticated": true
}
and I now want to give that JSON to a DisplayAnimal.vue at /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>
How would I do that? I know I can redirect via this.$router.push({ path });, but I've only used it for navigation, while here JSON response needs to be passed. Is this even a correct / good practice way of approaching this?
EDIT:
I tried this:
in GetAnimal.vue I added this data:
data: function() {
return {
animal: {
name: 'Cat',
furColor: 'red',
population: '10000',
isExtinct: false,
isDomesticated: true
}
and in DisplayAnimal.vue this:
<script>
export default {
props: {
animal: {
name: {
type: String
},
furColor: {
type: String
},
population: String,
isExtinct: String,
isDomesticated: String
}
}
}
</script>
and in GetAnimal.vue I added this:
methods: {
animals: function() {
alert("animals");
this.$router.push({name: 'viewanimal',
query: {animal: JSON.stringify(this.animal)}});
},
to try to display that test animal using the display component. However it just didn't work - I get an empty page.
Using Vuex, you can solve this easily
Working example on netlify
https://m-animalfarm.netlify.app/
code on github
https://github.com/manojkmishra/animalfarm
GetAnimal.vue ( I have disabled axios call for testing and hardcoded info)
<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),
this.info={"fur-color": "yellow","population": 51000,"isExtinct":
false,"isDomesticated": true },
this.$store.dispatch('storeAnimals', this.info)
//);
}
}
}
</script>
DisplayAnimal.vue
<template>
<div>
<p>Animal name: {{stateAnimal.animal}}</p>
<p>Fur color: {{stateAnimal.furColor}}</p>
<p>Population: {{stateAnimal.population}}</p>
<p>Is extinct: {{stateAnimal.isExtinct}}</p>
<p>Is domesticated: {{stateAnimal.isDomesticated}}</p>
</div>
</template>
<script>
import {mapState, mapGetters} from 'vuex';
export default {
computed:{ ...mapState({ stateAnimal:state => state.modulename.stateAnimal }),
},
}
</script>
modulename.js ( store module)
export default
{
state: {stateAnimal:null, },
getters:{ },
mutations:
{ ['STORE_ANIMALS'] (state, payload)
{ state.stateAnimal = payload;
console.log('state=',state)
},
},
actions:
{ storeAnimals: ({commit}, data) =>
{ console.log('storeanim-data-',data);
commit( 'STORE_ANIMALS', data );
},
}
}
Index.js (for vuex store), you can disable persistedstate as its for saving state if page is refreshed
import Vue from 'vue'
import Vuex from 'vuex'
import modulename from './modules/modulename'
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex)
export default new Vuex.Store({
plugins: [createPersistedState({ storage: sessionStorage })],
state: { },
mutations: { },
actions: { },
modules: { modulename }
})
State is available/shared for all the components
well first of all create a second folder call it services and create service.js for you axios call- good practice and cleaner code overall.
second use vuex. this kind of data is best used with vuex.
As far as I understand GetAnimal.vue is the parent component and you wish to display it in the child component DisplayAnimal.vue.
If so and you wish to see if this works just use props.
you can also send that same information or any other information for the child back to the parent using an $emit().
STRONGLY recommended to use vuex in order to manage the state
Vue.component('product',{
props:{
message:{
type:String,
required:true,
default:'Hi.'
}
},
template:`<div>{{message}}</div>`,
data(){...}
})
//html in the other component you axios call is in this component //<product meesage="hello"></product>
I would pass the animal name/id as a route param to the display page and have that component responsible for fetching and displaying the relevant animal data. This avoids the situation where a user could visit the display page directly via the URL and see an incomplete page.
In situations where you want to share local state between pages, as others have pointed out you'd probably want to use Vuex.
EDIT:
I'm adding some code to my answer as requested by the OP.
Routes:
const routes = [
{ path: "/", component: SearchAnimals },
{ path: "/viewanimal/:name", component: DisplayAnimal, name: "displayAnimal" }
];
DisplayAnimal.vue:
<template>
<div>
<p>Animal name: {{animal.name}}</p>
<p>Fur color: {{animal.furColor}}</p>
<p>Population: {{animal.population}}</p>
<p>Is extinct: {{animal.isExtinct}}</p>
<p>Is domesticated: {{animal.isDomesticated}}</p>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "DisplayAnimal",
data: () => ({
animal: {}
}),
methods: {
fetchAnimal(name) {
axios
.get(`http://localhost:8088/animalsapi?animal=${name}`)
.then(response => {
this.animal = response.data;
});
}
},
created() {
this.fetchAnimal(this.$route.params.name);
}
};
</script>
SearchAnimals.vue:
<template>
<form v-on:submit.prevent="onSubmit">
<textarea
v-model="animal"
name="animal"
type="animal"
id="animal"
placeholder="Enter your animal here"
></textarea>
<button type="submit">Get animal</button>
</form>
</template>
<script>
export default {
name: "SearchAnimal",
data: () => ({
animal: ""
}),
methods: {
onSubmit() {
this.$router.push({
name: "displayAnimal",
params: { name: this.animal }
});
}
}
};
</script>
Obviously this is a bare-bones example, so doesn't contain any error handling etc., but it should get you up and running.

Categories