Looping through nested arrays using VUEJS - vuejs2

/I have the following JSON data. I need to list students doing a particular subject. How can this be done using v-for in VUEJS?/
students_subjects:
[
{
student_id:1,
student_name:"Moses",
reg_no:"ABC/2019",
subjects:[
{
subject_id:1
subject_name:"English"
},
{
subject_id:2
subject_name:"Maths"
}
]
},
{
student_id:2,
student_name:"James",
reg_no:"ABD/2019",
subjects:[
{
subject_id:1
subject_name:"English"
},
{
subject_id:2
subject_name:"Maths"
}
]
}
]
// My structure of html code is as shown below
<div id="app">
<ul>
<li v-for="item in students">
<div class="row " style="background-color: #f4fbee;">
<div class="col-md-2">{{item.reg_no}}</div>
</div>
<div class="row" v-for="subjects in item.subjects">{{subjects.subject_name}}
</div>
</li>
</ul>
<pre>{{students}}</pre>
<p>{{getStudentsBySubjectId}}</p>
</div>
var appVM=new Vue({
el:"#app",
data:function(){
return {
student_id: '',
reg_no:'',
student_name:'',
students:Array(),
subjects:{},
}
},
created:function (){
this.getAllStudents();
},
methods:{
getAllStudents:function(){
var self=this;
axios.get("/Students/list").then(function (response) {
this.students = response.data;
}.bind(this)).catch(function (error) {
console.log('Error while fetching student data: ' + error)
})
},
getStudentsBySubjectId:function (students, subjectId) {
return students.filter(function(student) {
return student.subjects.some(function(subject) {
return subject.subject_id === subjectId;
})
})
}
},
})
</script>
// How do we get to display the filtered students.
//The code above shows the data returned on on calling the array on the view

Assuming that you are using ES6.
Here's how you would find all the students taking a particular subject:
function getStudentsBySubjectId(students, subjectId) {
return students.filter(student => student.subjects.some(subject => subject.subject_id === subjectId))
}
For ES5, use normal functions instead of arrow functions:
function getStudentsBySubjectId(students, subjectId) {
return students.filter(function(student) {
return student.subjects.some(function(subject) {
return subject.subject_id === subjectId;
})
})
}
you can simply v-for over the array returned by the above function.

Related

getting promise instead of value in laravel vue js [duplicate]

I am calling an async function which loads the profile pic, the await call returns the value to the variable 'pf' as expected, but I couldn't return that from loadProfilePic. At least for the start I tried to return a static string to be displayed as [object Promise] in vue template.
But when I remove await/asnyc it returns the string though.
<div v-for="i in obj">
{{ loadProfilePic(i.id) }}
</div>
loadProfilePic: async function(id) {
var pf = await this.blockstack.lookupProfile(id)
return 'test data';
//return pf.image[0]['contentUrl']
},
That is because async function returns a native promise, so the loadProfilePic method actually returns a promise instead of a value. What you can do instead, is actually set an empty profile pic in obj, and then populate it in your loadProfilePic method. VueJS will automatically re-render when the obj.profilePic is updated.
<div v-for="i in obj">
{{ i.profilePic }}
</div>
loadProfilePic: async function(id) {
var pf = await this.blockstack.lookupProfile(id);
this.obj.filter(o => o.id).forEach(o => o.profilePic = pf);
}
See proof-of-concept below:
new Vue({
el: '#app',
data: {
obj: [{
id: 1,
profilePic: null
},
{
id: 2,
profilePic: null
},
{
id: 3,
profilePic: null
}]
},
methods: {
loadProfilePic: async function(id) {
var pf = await this.dummyFetch(id);
this.obj.filter(o => o.id === id).forEach(o => o.profilePic = pf.name);
},
dummyFetch: async function(id) {
return await fetch(`https://jsonplaceholder.typicode.com/users/${id}`).then(r => r.json());
}
},
mounted: function() {
this.obj.forEach(o => this.loadProfilePic(o.id));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="i in obj">
{{ i.profilePic }}
</div>
</div>

input field value keeps getting reset #input?

I have created an custom reusable autocomplete component.The issue i am facing is whenever i start to type anything into the fields(#input) the value in the input field gets reset. I feel it has something to do within the code written in the debounce function but i am not sure.Plz help?
main.js
Vue.component('AutoComplete', {
props: ['list','value','title'],
data() {
return {
input: '',
}
},
template: `<template>
<div class="autocomplete">
<input style="font-size: 12pt; height: 36px; width:1800px; " type="text" v-model="input" #input="handleInput"/>
<ul v-if="input" >
<li v-for="(item, i) in list" :key="i" #click="setInput(item)" >
<template v-if="title!='manager'">
<div class="container">
<p>
<b>ID:</b>
{{item.id}}
</p>
<p>
<b>Description:</b>
{{item.description}}
</p>
</div>
</template>
<template v-else>
<div class="container">
<p>
<b>ID:</b>
{{item.id}}
</p>
<p>
<b>First Name:</b>
{{item.firstName}}
</p>
<p>
<b>Last Name:</b>
{{item.lastName}}
</p>
</div>
</template>
</li>
</ul>
</div>
</template>`,
methods: {
handleInput(e) {
console.log('inside handleInput')
this.$emit('input', e.target.value)
},
setInput(value) {
console.log('inside setInput')
this.input = value
this.$emit('click', value)
}
},
watch: {
$props: {
immediate: true,
deep: true,
handler(newValue, oldValue) {
console.log('new value is'+newValue)
console.log('old value is'+oldValue)
console.log('value inside handler'+this.value)
console.log('list inside handler'+this.list)
console.log('title inside handler'+this.title)
this.input=this.value
}
}
}
})
Currently i have called this component from JobDetail.vue page like this-
JobDetail.vue
<template>
<b-field label="Custom Action">
<AutoComplete v-on:input="getAsyncDataAction" v-on:click="(option) => {updateRowValue('records', props.index, 'action', option.id); props.row.action = option.id}" :value="props.row.action" :list="dataAction" title='action' >
</AutoComplete>
</b-field>
</template>
<script>
import { viewMixin } from "../viewMixin.js";
import debounce from "lodash/debounce";
import api from "../store/api";
const ViewName = "JobDetail";
export default {
name: "JobDetail",
mixins: [viewMixin(ViewName)],
data() {
return {
dataAction: [],
isFetching: false
};
},
methods: {
getAsyncDataAction: debounce(function(name) {
if (!name.length) {
this.dataAction = [];
return;
}
this.isFetching = true;
api
.getSearchData(`/action/?query=${name}`)
.then(response => {
this.dataAction = [];
response.forEach(item => {
this.dataAction.push(item);
});
})
.catch(error => {
this.dataAction = [];
throw error;
})
.finally(() => {
this.isFetching = false;
});
}, 500)
}
};
</script>
viewmixin.js
computed: {
viewData() {
return this.$store.getters.getViewData(viewName)
},
objectData() {
return this.$store.getters.getApiData(this.viewData.api_id).data
},
sessionData() {
return this.$store.getters.getSessionData()
},
isLoading() {
return this.$store.getters.getApiData(this.viewData.api_id).isLoading
},
newRecord() {
return this.$route.params.id === null;
}
},
I don't understand why the input fields value keeps resetting #input. Please help and also let me know if this is the correct approach?

v-for loop only array correspond to the dynamic page number

I store results per page number, see below:
<ul v-for="iten in listingsData" :key="item.id">
<li>{{ item.name }}</li>
</ul>
<button #click="pushPrev">Push Prev Results</button>
<button #click="pushNext">Push Next Results</button>
export default {
data(){
return {
listingsData : [],
page : 1
}
},
methods : {
pushNext(){
var _self = this;
axios.get('https://myapi.com/get/users?page='+this.page+1).then(function(response){
_self.page = _self.page + 1;
_self.listingsData = _self.listingsData.push({
page : _self.page,
results : response.data.results
})
});
},
pushPrev(){
var _self = this;
axios.get('https://myapi.com/get/users?page='+this.page-1).then(function(response){
_self.page = _self.page + 1;
_self.listingsData = _self.listingsData.push({
page : _self.page,
results : response.data.results
})
});
}
}
created(){
//load default data
var _self = this;
axios.get('https://myapi.com/get/users?page='+this.page).then(function(response){
_self.listingsData = {
page : 1,
results : response.data.results
}
});
}
}
Now how I can show or loop only results correspond to the the page number this.page?
_self.listingsData = _self.listingsData.push({
page : _self.page, // page number
results : response.data.results
})
What can I try?
I'm using Vue CLI and webpack.
You should iterate over computed property that will return specific page from listingsData, not over all pages.
Something like that:
<template>
<div v-if="currentPage">
<ul v-for="item in currentPage.results" :key="item.id">
<li>{{ item.name }}</li>
</ul>
</div>
<div v-else><i>Loading...</i></div>
<button #click="fetchPage(-1)" :disabled="page===1">Prev Results</button>
<button #click="fetchPage(1)" :disabled="page===10">Next Results</button>
</template>
<script>
const api = "https://myapi.com/get/users";
export default {
data() {
return {
page: 1,
listingsData: [],
};
},
created() {
this.fetchPage(0);
},
computed: {
currentPage() {
return this.listingsData.find(i => i.page === this.page);
},
},
methods: {
fetchPage(diff) {
this.page += diff;
if (this.currentPage) {
return; // page already loaded
}
const page = this.page;
axios.get(api, { params: { page } })
.then((res) => {
this.listingsData.push({
page,
results: res.data.results,
});
});
},
}
};
</script>
Here, we're loading page only if it hasn't been loaded before, and disable Prev/Next buttons if current page is 1/10 respectively.
Here is jsfiddle (with mockup data instead of actual API calls).

Vue.js data: undefined

I am new to Vue.js.
Please advice me.
I get comments: undefined so comments are not displaying.
xhr is normal with 200.
Thank you
Thank you
Thank you
Thank you
Thank you
<template>
<div>
<ul class="media-list">
<li class="media" v-for="comment in comments">
{{ $comment.body }}
</li>
</ul>
</div>
</template>
<script>
export default {
data () {
return {
comments: []
}
},
props: {
postid: null
},
methods: {
getComments () {
this.$http.get('/blog/' + this.postid + '/comments').then((response) => {
this.comments = response.json().data;
});
}
},
mounted () {
this.getComments();
}
}
Basically there are two problems:
$comment don't exist
You have no data on response.json().data, that's why you get a undefined
I used a different API just to test it (as I don't have access to yours).
TEMPLATE
<div id="app">
<ul class="media-list">
<li class="media" v-for="comment in comments">
{{ comment.familyName + ', ' + comment.givenName }}
</li>
</ul>
</div>
SCRIPT
new Vue({
el: '#app',
data () {
return {
comments: []
}
},
props: {
postid: null
},
methods: {
getComments () {
this.$http.get('//ergast.com/api/f1/drivers.json').then((response) => {
this.comments = response.body.MRData.DriverTable.Drivers;
});
}
},
mounted () {
this.getComments();
}
});
Check out a working example here
this.comments = response.json().data;
console.log(this.comments) ;
to see what you get ;
you define comments=Array ;
maybe you get the response.json().data is not a Array;
Try using vm instead of this. In API response make sure what you are getting using console.log(). If response is already in json do not use response.json(). In HTML change $comment.body to comment.body. Make sure you have the body key in comments[] array.
<template>
<div>
<ul class="media-list">
<li class="media" v-for="comment in comments">
{{ comment.body }}
</li>
</ul>
</div>
</template>
<script>
export default {
data () {
return {
comments: [],
postid: null
}
},
props: {
},
methods: {
getComments () {
let vm = this;
vm.$http.get('/blog/' + vm.postid +
'/comments').then((response) => {
console.log(response)
vm.comments = response.data;
});
}
},
mounted () {
let vm = this;
vm.getComments();
}
}
}
:
My suggestion is to properly use try-catch statements.
I have found this is the safest and proper way to manage cases where variable could take undefined or null values, instead of trying to "if" everything.
try {
val = localStorage.getItem('accesstoken')
} catch (error) {
alert(error)
}
Take care!

Vuejs reactive v-if template component

I'm struggling to understand how to make my component reactive. At the moment the button is rendered correctly but once the create/delete event happens, the template does not change. Any tips on how to update the component after the event has taken place?
new Vue({
el: '#app'
});
Vue.component('favourite-button', {
props: ['id', 'favourites'],
template: '<input class="hidden" type="input" name="_method" value="{{ id }}" v-model="form.listings_id"></input><button v-if="isFavourite == true" class="favourited" #click="delete(favourite)" :disabled="form.busy"><i class="fa fa-heart" aria-hidden="true"></i><button class="not-favourited" v-else #click="create(favourite)" :disabled="form.busy"><i class="fa fa-heart" aria-hidden="true"></i></button><pre>{{ isFavourite == true }}</pre>',
data: function() {
return {
form: new SparkForm({
listings_id: ''
}),
};
},
created() {
this.getFavourites();
},
computed: {
isFavourite: function() {
for (var i = 0; this.favourites.length; i++)
{
if (this.favourites[i].listings_id == this.id) {
return true;
}
}
},
},
methods: {
getFavourites() {
this.$http.get('/api/favourites')
.then(response => {
this.favourites = response.data;
});
},
create() {
Spark.post('/api/favourite', this.form)
.then(favourite => {
this.favourite.push(favourite);
this.form.id = '';
});
},
delete(favourite) {
this.$http.delete('/api/favourite/' + this.id);
this.form.id = '';
}
}
});
Vue.component('listings', {
template: '#listing-template',
data: function() {
return {
listings: [], favourites: [],
};
},
created() {
this.getListings();
},
methods: {
getListings() {
this.$http.get('/api/listings')
.then(response => {
this.listings = response.data;
});
}
}
});
Vue expects HTML template markups to be perfect. Otherwise you will run into multiple issues.
I just inspected your template and found an issue - the first <button> element does not close.
Here is the updated version of your code:
Vue.component('favourite-button', {
props: ['id', 'favourites'],
template: `
<input class="hidden" type="input" name="_method" value="{{ id }}" v-model="form.listings_id"></input>
<button v-if="isFavourite == true" class="favourited" #click="delete(favourite)" :disabled="form.busy">
<i class="fa fa-heart" aria-hidden="true"></i>
</button> <!-- This is missing in your version -->
<button class="not-favourited" v-else #click="create(favourite)" :disabled="form.busy">
<i class="fa fa-heart" aria-hidden="true"></i>
</button>
<pre>{{ isFavourite == true }}</pre>
`,
...
Note the comment on 7th line above, the closing </button> tag is not present in your template.
As a side note, if you do not want to type back-slash at the end of every line to make multi-line template strings, you can use back-ticks as shown in my code example above. This will help you avoid markup errors leading to Vue component issues and many hours of debugging.
Another reference: Check out "Multi-line Strings" in this page: https://developers.google.com/web/updates/2015/01/ES6-Template-Strings
Relevant lines (copied from above page):
Any whitespace inside of the backtick syntax will also be considered part of the string.
console.log(`string text line 1
string text line 2`);
EDIT: Found a possible bug in code
Here is another issue in your create method of favourite-button component:
methods: {
// ...
create() {
Spark.post('/api/favourite', this.form)
.then(favourite => {
this.favourite.push(favourite); // Note: This is the problem area
this.form.id = '';
});
},
//...
}
Your success handler refers to this.favourite.push(...). You do not have this.favourite in data or props of your component. Shouldn't it be this.favourites?