in vue.js i am trying to get row count but it returning null - laravel

im trying to get row cout but returning 0 only.
my code
<template>
<div>
<p>{{ resultCount }}</p>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
registerlist: [],
};
},
async asyncData({ $axios }) {
let { data } = await $axios.$get("/Businessregisterlist");
// console.log(response)
return {
registerlist: data,
};
},
computed: {
resultCount() {
return Object.keys(this.registerlist).length;
},
},
};
</script>

This is because when you return a property in asyncData, you should not have it in data property of the component instance, instead the later will override the returned with asyncData.
<script>
import axios from "axios";
export default {
async asyncData({ $axios }) {
let { data } = await $axios.$get("/Businessregisterlist");
// console.log(response)
return {
registerlist: data,
};
},
computed: {
resultCount() {
return Object.keys(this.registerlist).length;
},
},
};
</script>
<template>
<div>
<p>{{ resultCount }}</p>
</div>
</template>

Related

how to get each data from response api laravel in vue js 3

Need help , i can get all data from response api but having some problem when try to get data (looping data ) from key "get_item_cards" . Here's my response and code in vue js
Response api
<script setup>
<script>
import axios from 'axios'
export default {
name: 'ListNotes',
data() {
return {
cardNotes: [],
}
},
mounted() {
// console.log('Page mounted');
this.getListNotes();
},
methods: {
getListNotes() {
axios.get('http://localhost:8000/api/card').then(res => {
this.cardNotes = res.data.cardNotes
console.log(this.cardNotes);
})
}
}
}
</script>
how the best way to get all data & each data from relationship in vue js 3
Since the this.cardNote returns an array with three elements, you can use loop using v-for and access to the get_item_cards array like below,
<template>
<div>
<div v-for=(note, index) in cardNote>
<p>{{node.cardname}}</p>
<div v-for=(item, key) in note.get_item_cards>
<p>{{item.content}}</p>
</div>
</div>
</div>
</template>
<script setup>
<script>
import axios from 'axios'
export default {
name: 'ListNotes',
data() {
return {
cardNotes: [],
}
},
mounted() {
// console.log('Page mounted');
this.getListNotes();
},
methods: {
getListNotes() {
axios.get('http://localhost:8000/api/card').then(res => {
this.cardNotes = res.data.cardNotes
console.log(this.cardNotes);
})
}
}
}
</script>

Show component only after all images loaded

I am using Vue 3 and what i would like to achieve is to load all images inside a card (Album Card) and only then show the component on screen..
below is an how it looks now and also my code.
Does anybody have an idea how to achieve this?
currently component is shown first and then the images are loaded, which does not seem like a perfect user experience.
example
<template>
<div class="content-container">
<div v-if="isLoading" style="width: 100%">LOADING</div>
<album-card
v-for="album in this.albums"
:key="album.id"
:albumTitle="album.title"
:albumId="album.id"
:albumPhotos="album.thumbnailPhotos.map((photo) => photo)"
></album-card>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import albumCard from "#/components/AlbumCard.vue";
interface Album {
userId: number;
id: number;
title: string;
thumbnailPhotos: Array<Photo>;
}
interface Photo {
albumId: number;
id: number;
title: string;
url: string;
thumbnailUrl: string;
}
export default defineComponent({
name: "Albums",
components: {
albumCard,
},
data() {
return {
albums: [] as Album[],
isLoading: false as Boolean,
};
},
methods: {
async getAlbums() {
this.isLoading = true;
let id_param = this.$route.params.id;
fetch(
`https://jsonplaceholder.typicode.com/albums/${
id_param === undefined ? "" : "?userId=" + id_param
}`
)
.then((response) => response.json())
.then((response: Album[]) => {
//api returns array, loop needed
response.forEach((album: Album) => {
this.getRandomPhotos(album.id).then((response: Photo[]) => {
album.thumbnailPhotos = response;
this.albums.push(album);
});
});
})
.then(() => {
this.isLoading = false;
});
},
getRandomPhotos(albumId: number): Promise<Photo[]> {
var promise = fetch(
`https://jsonplaceholder.typicode.com/photos?albumId=${albumId}`
)
.then((response) => response.json())
.then((response: Photo[]) => {
const shuffled = this.shuffleArray(response);
return shuffled.splice(0, 3);
});
return promise;
},
/*
Durstenfeld shuffle by stackoverflow answer:
https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array/12646864#12646864
*/
shuffleArray(array: Photo[]): Photo[] {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
},
},
created: function () {
this.getAlbums();
},
});
</script>
What i did to solve this problem was using function on load event on (img) html tag inside album-card component. While images are loading a loading spinner is shown. After three images are loaded show the component on screen.
<template>
<router-link
class="router-link"
#click="selectAlbum(albumsId)"
:to="{ name: 'Photos', params: { albumId: albumsId } }"
>
<div class="album-card-container" v-show="this.numLoaded == 3">
<div class="photos-container">
<img
v-for="photo in this.thumbnailPhotos()"
:key="photo.id"
:src="photo.thumbnailUrl"
#load="loaded()"
/>
</div>
<span>
{{ albumTitle }}
</span>
</div>
<div v-if="this.numLoaded != 3" class="album-card-container">
<the-loader></the-loader>
</div>
</router-link>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import { store } from "#/store";
export default defineComponent({
name: "album-card",
props: {
albumTitle: String,
albumsId: Number,
},
data: function () {
return {
store: store,
numLoaded: 0,
};
},
methods: {
thumbnailPhotos() {
return this.$attrs.albumPhotos;
},
selectAlbum(value: string) {
this.store.selectedAlbum = value;
},
loaded() {
this.numLoaded = this.numLoaded + 1;
},
},
});
</script>
Important note on using this approach is to use v-show instead of v-if on the div. v-show puts element in html(and sets display:none), while the v-if does not render element in html so images are never loaded.

How can I update my VueJs Data function properties value while fetching data from API using axios?

I have successfully fetched data from API. The fetched data shows in the alert function. However, the properties in the data function such as - 'Recovered' is not updating. I can show the fetched data using Vanilla JS. But I want to update them automatically and want to show them like this {{Recovered}}.
How can I do it??
<template>
<div class="container">
<h2>Total Recovered: {{Recovered}}</h2>
</div>
</template>
<script>
import axios from 'axios'
export default {
name:'CoronaStatus',
data: function () {
return {
Recovered: '',
TotalConfirmed: '',
TotalDeaths: '',
// test: '30',
// test_2: 'maheeb',
// componentKey: 0,
}
},
mounted(){
this.globalStatus();
},
methods:{
globalStatus: function(){
// const self = this;
// this.componentKey += 1;
axios.get('https://api.covid19api.com/summary')
.then((response) => {
// this.recovered = response.data.Global.NewConfirmed;
this.Recovered= response.data.Global.TotalRecovered;
alert(this.Recovered);
// document.getElementById('test_5').innerHTML = "total: " + this.TotalRecovered;
}).catch(err=> console.log(err));
},
}
}
</script>
<style scoped>
</style>
The easiest solution would be to refetch the information every hour with setInterval.
The best solution would be to use the WebHook provided by covid19api.com.
Vue.config.devtools = false;
Vue.config.productionTip = false;
var app = new Vue({
el: '#app',
data: {
Recovered: "Loading ..."
},
mounted() {
setInterval(() => {
this.globalStatus();
}, 3600000); // Call globalStatus every hour
this.globalStatus();
},
methods: {
globalStatus: function() {
axios
.get("https://api.covid19api.com/summary")
.then(response => {
this.Recovered = response.data.Global.TotalRecovered;
})
.catch(err => console.log(err));
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<div id="app">
<h2>Total Recovered: {{ Recovered }}</h2>
</div>

How to display data on blade from Vue Js?

I had grabbed some code for test purpose, I have tried to fixing "item not define" error but I am stuck.
//Blade View
<v-app id="app" v-cloak><div class="card" :posts="{{$posts}}"></div></v-app>
//Vuejs template
<table striped hover :items="imageList"> <img :scr="'/storage/image/'+data.items.image"></table>
Vue Js:
<script>
export default {
// name: "ExampleComponent",
props: \['posts'\],
data() {
return {
imageList: \[\]
};
},
mounted() {
const fetch = this.fetch_image_list();
},
methods: {
fetch_image_list() {
let items = \[\];
if (Array.isArray(this.posts.data) && this.posts.length.data) {
this.posts.data.forEach((post, key) => {
let currentImage = {
id: post.id,
name: post.name,
image: post.img
};
items.push(currentImage);
});
this.imageList = items;
}
}
}
};
</script>]
item is not define
Isn't it because you are "calling" :
data.items.image instead of items[index].image ?

Display passed image in template, in VUE

So I have this code:
<template>
<div id="search-wrapper">
<div>
<input
id="search_input"
ref="autocomplete"
placeholder="Search"
class="search-location"
onfocus="value = ''"
#keyup.enter.native="displayPic"
>
</div>
</div>
</template>
<script>
import VueGoogleAutocomplete from "vue-google-autocomplete";
export default {
data: function() {
return {
search_input: {},
pic: {}
};
},
mounted() {
this.autocomplete = new google.maps.places.Autocomplete(
this.$refs.autocomplete
);
this.autocomplete.addListener("place_changed", () => {
let place = this.autocomplete.getPlace();
if (place.photos) {
place.photos.forEach(photo => {
let pic=place.photos[0].getUrl()
console.log(pic);
});
}
});
},
methods: {
displayPic(ref){
this.autocomplete = new google.maps.places.Autocomplete(
this.$refs.autocomplete);
this.autocomplete.addListener("place_changed", () => {
let place = this.autocomplete.getPlace();
if (place.photos) {
place.photos.forEach(photo => {
let pic=place.photos[0].getUrl()
console.log(pic);
});
}
})
},
}
}
I want to pass the "pic" parameter, resulted in displayPic, which is a function, into my template, after one of the locations is being selected.
I've tried several approaches, but I'm very new to Vue so it's a little bit tricky, at least until I'll understand how the components go.
Right now, the event is on enter, but I would like it to be triggered when a place is selected.
Any ideas how can I do that?
Right now, the most important thing is getting the pic value into my template.
<template>
<div id="search-wrapper">
<div>
<input style="width:500px;"
id="search_input"
ref="autocomplete"
placeholder="Search"
class="search-location"
onfocus="value = ''"
v-on:keyup.enter="displayPic"
#onclick="displayPic"
>
<img style="width:500px;;margin:5%;" :src="pic" >
</div>
</div>
</template>
<script>
import VueGoogleAutocomplete from "vue-google-autocomplete";
export default {
data: function() {
return {
search_input: {},
pic:""
};
},
mounted() {
this.autocomplete = new google.maps.places.Autocomplete(
this.$refs.autocomplete,
{componentRestrictions: {country: "us"}}
);
},
methods: {
displayPic: function(){
this.autocomplete.addListener("place_changed", () => {
let place = this.autocomplete.getPlace();
if (place.photos) {
place.photos.forEach(photo => {
this.pic=place.photos[0].getUrl()
});
}
})
},
}
}
</script>

Resources