get query value from url VueJs - javascript

I'm new vuejs learner and I want to get the query value from url to use it in the vue method as explained below.
This is the route:
{
path: "/FetchData/:query?",
name: "FetchData",
component: FetchData,
}
And this is the link to redirect to the second page
<router-link :to="{ path: '/FetchData', query: { query: country.countryName }}">
this is the api
public IActionResult GetSubs(string query, int? subs)
{
return Ok(SubService.GetSubs(query, subsId));
}
This is the vue method calling the api
getSubs() {
axios.get("https://localhost:44391/api/Subs/GetSubs")
.then(res => this.subs = res.data)
.catch(err => console.log(err))
}
And finally, this is the html to display data
<div class="d-flex flex-row mb-3">
<div class="d-flex flex-column ml-2"><span>{{subs.subsId}}</span></div>
</div>
<h6 style="text-align:left">{{subs.label}}</h6>

if you're using vuejs 2 you can access query using: this.$route.query
but if you're using v3 it should be something like:
import { useRoute } from 'vue-router'
import { computed } from 'vue';
export default {
setup() {
const route = useRoute()
return {
query: computed( () => route.query )
}
}
}
then you can use this.query inside your method

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.

Vue use route params for axios get request

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} });

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 get data from firebase when page loading using vuejs?

I have been trying to get current user data from firebase to display details in profile page.
Here i am trying get data from firestore, when page loading. My table structure : users => Current user UID => email, firstname, lastname, businessname, etc.
I have added functionality to get data from firebase when profile page loading but does not work. error showing in console product.data().firstname is not function.
And also i did not get any console output firebase data retrieved or not?
here is my code:
<template>
<section class="what-we-do">
<div class="container-2" style="padding-top: 150px;">
<div class="row">
<div class="col-md-12">
<div class="saving-process-crd">
<div class="saving-process-inner">
<avatar :fullname="currentUser.email" size="96" >
</avatar>
<h4>Siva NSN</h4>
<h6 style="color:grey;">{{currentUser.email}}</h6><br><br>
<div class="card-columns" >
<div class="card" style="border: none; text-align: justify;">
<div class="card-body">
<h5 class="card-title">First Name:</h5><br>
<h5 class="card-title">Last Name:</h5><br>
<h5 class="card-title">Email ID:</h5><br>
</div>
</div>
<div class="card" style="border: none;">
<div class="card-body" style="float: left; text-align: left;" >
<h5 class="card-title">{{product.data().firstname}}</h5><br>
<h5 class="card-title">Mobility</h5><br>
<h5 class="card-title">{{currentUser.email}}</h5><br>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</template>
<script>
import Avatar from 'vue-avatar-component'
import database from '#/database'
import firebase from 'firebase/app'
export default {
name: 'Profile',
computed:{
currentUser (){
return this.$store.state.currentUser
}
},
components: {
Avatar
},
data () {
return {
profileData:{
email:null,
firstname:null,
lastname:null,
secondaryEmail:null,
businessName:null
}
}
},
methods:{
readData(){
const firestore = database.firestore();
firestore.collection('users').doc(firebase.auth().currentUser.uid).
onSnapshot(function(doc){
console.log('current data:', doc.data())
var newData = doc.data()
this.profileData.push(newData)
})
}
}
}
</script>
main.js code:
here i am i have user authstatechanges of current user.
import Vue from 'vue'
import App from './App.vue'
import router from './router';
import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import './assets/styles//base-style.css';
import store from '#/store'
import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/firestore'
Vue.config.productionTip = false
let app
const initialize = () => {
if (!app) {
app = new Vue({
el: '#app',
router,
store,
render: h => h(App),
})
}
}
firebase.auth().onAuthStateChanged(user => {
if(user) {
store.commit('setCurrentUser', user)
} else {
store.commit('setCurrentUser', null)
}
initialize()
})
console output:
How to get data when page loading from firebase database. any help much appreicated pls..
There are number of things you have to adjust,
instead of fetching data using a method, try to add the code to a life cycle hook method, which will fire before you mount the data to dom, more precisely saying, use created lifecycle hook
https://vuejsexamples.net/vuejs-created/
Then you are populating the data to the template using currentUser which is taken from the vuex store,
return this.$store.state.currentUser, but in your firebase function you are setting the data you fetch to a data property which is profileData which is not used in the template.
You are pushing to profileData, but it's not an array it is a object and you cant push to an object.
So better flow is, fetch data using created lifecycle hook, then
either
store(mutate) the received data to the store.state.currentUser then it might work.
else update the profileData and replace the template with profileData instead of currentUser
Try this one,
Create a created lifecycle hook and move the firebase code to that. and assign the profileData object to the fetched Data.
created() {
const firestore = database.firestore();
firestore.collection('users').doc(firebase.auth().currentUser.uid).
onSnapshot(function(doc){
console.log('current data:', doc.data())
var newData = doc.data()
this.profileData = newData;
})
}
Then replace the currentUser in template to profileData.
ex : <h6 style="color:grey;">{{profileData.email}}</h6><br><br>

VUE.JS after parsing trough the JSON getting wrong output

I did [GET] method using Axios. Everything is working fine, when I want to output i get this kind of thing:
http://prntscr.com/mpey70
This is my JS with HTML and VUE code on how I am trying to output it:
HTML, VUE:
<div class="col-lg-6">
<p>Casuals</p>
<ul>
<div v-bind:key="realsub.id+1" v-for="realsub in subnavreal">
<div v-if="nav.linkTitle == 'Male'">
<li><router-link :to="{ path: whiteSpace(realsub.male.casual) }">{{JSON.realsub.male.casual}}</router-link></li>
</div>
<div v-if="nav.linkTitle == 'Female'"></div>
<li><router-link :to="{ path: whiteSpace(realsub.female.casual) }">{{realsub.female.casual}}</router-link></li>
</div>
</ul>
</div>
And this is Related JS code:
import axios from 'axios';
import uuid from 'uuid';
export default {
name: 'navigation',
data(){
return{
subnavreal: []
}
},
props: ["navigation"],
methods:{
whiteSpace(a){
console.log(a);
}
},
async created(){
axios.get('/products.json')
.then(res => this.subnavreal = res.data)
.catch(err => console.log(err));
}
}
</script>
What I want to display is only the name of that object, for example: "Hoodies"
Any solutions? :)
I think you are printing the entire Response. You can use the Object.keys() to print the keys.
let user = {
name: "tom",
age: 20
}
If you want to print the keys [name, age] use Object.keys(user)

Categories