How to render an array inside another object array with Vue Js - javascript

I am working with Laravel Vuejs, and from my database I obtain an object array called arrayService, through axios I perform a get where the array I obtain can be seen represented.
var app = new Vue({
el: '#app',
mounted() {
//this.getService()
},
data() {
return {
arrayService: [
{ service: '2', format: [".mp3",".mp4"] },
{ service: '3', format: [".jpg",".png"] },
],
arrayFormat: [".mp3",".mp4",".jpg",".png"]
}
},
methods:
{
getService() {
axios.get('/').then(function(response){
this.arrayService = response.data
/*I GET FROM THE DATABASE
arrayService: [
{ service: '2', format: [".mp3",".mp4"] },
{ service: '3', format: [".jpg",".png"] },
],
*/
$.each(response.data, function (key,value) {
$.each(JSON.parse( value.format ), (key,element) => {
this.arrayFormat.push(element)
/*RESULT OF PARSE:
arrayFormat: [
{ [".mp3",".mp4",".jpg",".png"] }
]
*/
})
})
})
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<div id="app">
<div>
<div class="row">
<div class="col-sm-6">
<h5>Wrong result :</h5>
<div v-for="service in arrayService" :key="service.id">
<strong>Id Service:</strong> {{service.service}}
<br>
<strong>Format:</strong>
<div v-for="format in arrayFormat" :key="format.id">
{{format}}
</div>
</div>
</div>
<div class="col-sm-6">
<h5>Correct result:</h5>
<strong>Id Service:</strong> 2
<br>
<strong>Format:</strong>
<br>
.mp3
<br>
.mp4
<br>
<strong>Id Service:</strong> 3
<br>
<strong>Format:</strong>
<br>
.jpg
<br>
.png
<br>
</div>
</div>
<br>
<br>
<br>
<br><br>
<br>
<br>
<br>
<br>
<br>
</div>
</div>
When I store the array arrayService, what I do is a Parse, inside the format attribute, since there is another array with the formats of each service. (see comments).
By doing this Parse, I finally do a push to store all these elements (formats) in an array called arrayFormat.
The problem I am having is that when doing that push, it stores everything together, and it is not what I am looking for.
What I am looking for is to store each format, regarding its service.
In the HTML view I tried to show the correct result, but the idea is to put all this together with VueJS.
Any idea?

You don't need the arrayFormat array at all, since the data structure you need is already in the API response.
You can iterate the nested array (service.format) directly:
<div v-for="service in arrayService" :key="service.service">
... 👇
<div v-for="format in service.format" :key="format">
{{format}}
</div>
</div>
new Vue({
el: '#app',
data() {
return {
arrayService: [{
service: '2',
format: [".mp3", ".mp4"]
},
{
service: '3',
format: [".jpg", ".png"]
},
],
}
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<div id="app">
<div v-for="service in arrayService" :key="service.service">
<strong>Id Service:</strong> {{service.service}}
<br>
<strong>Format:</strong>
<div v-for="format in service.format" :key="format">
{{format}}
</div>
</div>
</div>

Related

str.split() is splitting at every letter and not at the delimiter

I'm trying to split a string of tags that I'm getting back from firebase by ',' and then store them in my data() for rendering. When I render out the firebase snapshot data after I split they tags in the console they are correctly formatted like so:
"tag1" "tag2"
but when I render them in my vue app, they are split at every letter (or at least a div is generated and is displaying for every letter) like so:
<div>"t"</div>
<div>"a"</div>
<div>"g"</div>
<div>"1"</div>
Can someone let me know if this is an issue with my vue app or my firebase call?
I have included some dummy data that I'm using to show the final result of how the tags array in data should look.
Here's my app for reference :)
<div id="container">
<div class="topbar">
<h3 id="header">DevDeep</h3>
<div id="searchDiv">
<b-form-input id="search" v-model="search" placeholder="search articles"></b-form-input>
<font-awesome-icon id="searchBtn" #click="searchResults()" icon="search" />
</div>
</div>
<!--main part of page-->
<div class="bod">
<div class="sideContainer">
<h4 id="category">categories</h4>
<ul id="listoflinks" v-for="cat in categories" :key="cat.toString()">
<div #click="searchResultsByCat(cat)">{{cat}}</div>
</ul>
</div>
<div id="centerContainer">
<div>
<h5> Tag list </h5>
<div class="flexContainer">
<div id="selectedTags" v-for="tag in tagList" :key="tag.toString()">
<span id="tag" #click="removeTag(tag)">{{tag}}</span>
</div>
<font-awesome-icon id="searchBtn" #click="searchbyTags()" icon="search" />
</div>
</div>
<div id="artDiv" v-for="art in articles" :key="art.title">
<div #click="gotoArticle(art)" id="thumbnail">
<h5 >{{art.title}}</h5>
<img :src=art.image height="100px" width="100px" alt="article thumbnail">
</div>
<!--TAGS-->/////////////////////////////////////////
<div class="flexContainer">
<div id="tags" v-for="tag in art.tags" :key="tag.toString()">
<span id="tag" #click="addTagToSearch(tag)">{{tag}}</span>
</div>
</div>
<!--TAGS-->//////////////////////////////////////////
</div>
</div>
<div class="addContainer">adds</div>
</div>
<!--main part of page-->
</div>
</template>
<script>
const fb = require('../../fireconfig.js')
export default {
name: 'Home',
data:function() {
return{
articles: [
{
title: 'modern web app security',
body: 'some content here about web app security',
image: 'dd',
tags: ['cyber security','web apps', 'web development']
},
{
title: 'intro to ArcGIS',
body: 'an article to show users how to do GIS stuff',
image: 'dwwd',
tags: ['arcgis','node js','gps services']
},
{
title: 'Vue.js injecting props',
body: 'this is how to inject vue props into a component',
image: 'dwwd',
tags: ['vue','props','components','web development','web apps']
}
],
categories:['web development', 'arcgis','cyber security','partnerships'],
search: '',
tagList: []
}
},
props: {
post: Object
},
created(){
console.log('db post will go here later')
let ref = fb.db.collection('articles')
ref.get()
.then(snapshot => {
if (snapshot.empty) {
console.log('No matching documents.');
return;
}
snapshot.forEach(doc => { //this works for each doc
console.log(doc.id, '=>', doc.data());
doc.data().tags = doc.data().tags.split(",") // its splitting each letter we need to only split at the comma
console.log(doc.data().tags)
this.articles.push(doc.data()) //push object into state array
})
})
.catch(err => {
console.log('Error getting documents', err);
});
},
}
</script>
doc.data() will produce a new object each time you call the method.
doc.data().tags = doc.data().tags.split(",") // its splitting each letter we need to only split at the comma
The above line is pointless you create a new object, but never store it in a variable. Which means that you can't use it later. Instead assign the resulting object to variable and use that.
const data = doc.data(); // create the data object only once
data.tags = data.tags.split(",");
this.articles.push(data);
Since the split of the tags didn't persist in the question code. tag in:
<div id="tags" v-for="tag in art.tags" :key="tag.toString()">
Is set to a character, because art.tags is a string and not an array.

Vue bootstrap b-form-select sets vuelidate's $anyDirty to true on load

The issue I'm having is due to the input event that's being run when I first set a value to the v-model, this data is being loaded in via an API; I understand why the form is being set to dirty (as this it is being changed) but this causes problems in another component I have which checks if the $v.$anyDirty flag is sets to true and if it is, creates a pop up to say "are you sure you want to navigate away" but calling $v.reset() after the data is loaded doesn't work.
Vue.use(vuelidate.default);
const { required } = window.validators;
new Vue({
el: "#app",
data: {
todos: [],
todo: ""
},
async created() {
var data = await axios.get("https://jsonplaceholder.typicode.com/todos");
this.todos = data.data.map(d => d.id);
this.todo = this.todos[0];
this.$v.$reset()
},
validations() {
return {
todo: { required }
};
}
});
<link href="https://unpkg.com/bootstrap-vue#2.0.0-rc.11/dist/bootstrap-vue.css" rel="stylesheet"/>
<link href="https://unpkg.com/bootstrap#4.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue#2.0.0-rc.11/dist/bootstrap-vue.min.js"></script>
<script src="https://unpkg.com/vuelidate#0.7.4/dist/validators.min.js"></script>
<script src="https://unpkg.com/vuelidate#0.7.4/dist/vuelidate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<div id='app'>
<div class="row">
<div class="col-md-4">
<b-form-select v-model="$v.todo.$model" :options="todos"></b-form-select>
</div>
<div class="col-md-8">
<code>
$anyDirty: {{$v.$anyDirty}}
</code>
</div>
</div>
</div>
The problem is that $v.reset() is being run before vue renders so the input events happen after, so the stack trace would look like this
load > set values > reset validation > render > input event
You need to put the reset inside Vue.nextTick and then it'll work as it'll change the execution to be
load > set values > render > input event > reset validation
Vue.use(vuelidate.default);
const {
required
} = window.validators;
new Vue({
el: "#app",
data: {
todos: [],
todo: ""
},
async created() {
var data = await axios.get("https://jsonplaceholder.typicode.com/todos");
this.todos = data.data.map(d => d.id);
this.todo = this.todos[0];
Vue.nextTick(() => {
this.$v.$reset()
})
},
validations() {
return {
todo: {
required
}
};
}
});
<link href="https://unpkg.com/bootstrap-vue#2.0.0-rc.11/dist/bootstrap-vue.css" rel="stylesheet" />
<link href="https://unpkg.com/bootstrap#4.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue#2.0.0-rc.11/dist/bootstrap-vue.min.js"></script>
<script src="https://unpkg.com/vuelidate#0.7.4/dist/validators.min.js"></script>
<script src="https://unpkg.com/vuelidate#0.7.4/dist/vuelidate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<div id='app'>
<div class="row">
<div class="col-md-4">
<b-form-select v-model="$v.todo.$model" :options="todos"></b-form-select>
</div>
<div class="col-md-8">
<code>
$anyDirty: {{$v.$anyDirty}}
</code>
</div>
</div>
</div>
As a note, you can also call Vue.nextTick with this.$nextTick

How do I fetch JSON data with Vue and Axios

I'm trying to fetch product data from a JSON file, but can't get it to work.
I've tried several things and searched the internet for a solution but none of the examples on the internet equals my situation.
I'm new to both vue and axios, so please excuse my ignorance.
This is what I have so far:
Vue.component('products',{
data: {
results: []
},
mounted() {
axios.get("js/prods.json")
.then(response => {this.results = response.data.results})
},
template:`
<div id="products">
<div class="productsItemContainer" v-for="product in products">
<div class="productsItem">
<div class="">
<div class="mkcenter" style="position:relative">
<a class="item">
<img class="productImg" width="120px" height="120px" v-bind:src="'assets/products/' + product.image">
<div class="floating ui red label" v-if="product.new">NEW</div>
</a>
</div>
</div>
<div class="productItemName" >
<a>{{ product.name }}</a>
</div>
<div class="mkdivider mkcenter"></div>
<div class="productItemPrice" >
<a>€ {{ product.unit_price }}</a>
</div>
<div v-on:click="addToCart" class="mkcenter">
<div class="ui vertical animated basic button" tabindex="0">
<div class="hidden content">Koop</div>
<div class="visible content">
<i class="shop icon"></i>
</div>
</div>
</div>
</div>
</div>
</div>
`
})
new Vue({
el:"#app",
});
The json file is as follows
{
"products":[
{
"name": "Danser Skydancer",
"inventory": 5,
"unit_price": 45.99,
"image":"a.jpg",
"new":true
},
{
"name": "Avocado Zwem Ring",
"inventory": 10,
"unit_price": 123.75,
"image":"b.jpg",
"new":false
}
]
}
The problem is only with the fetching of the data from a JSON file, because the following worked:
Vue.component('products',{
data:function(){
return{
reactive:true,
products: [
{
name: "Danser Skydancer",
inventory: 5,
unit_price: 45.99,
image:"a.jpg",
new:true
},
{
name: "Avocado Zwem Ring",
inventory: 10,
unit_price: 123.75,
image:"b.jpg",
new:false
}
],
cart:0
}
},
template: etc.........
As the warnings suggest, please do the following:
Rename the data array from results to products since you are referencing it by the latter one as a name during render.
Make your data option a function returning an object since data option must be a function, so that each instance can maintain an independent copy of the returned data object. Have a look at the docs on this.
Vue.component('products', {
data() {
return {
products: []
}
},
mounted() {
axios
.get("js/prods.json")
.then(response => {
this.products = response.data.products;
});
},
template: `
//...
`
}
<div id="products">
<div class="productsItemContainer" v-for="product in products">
<div class="productsItem">
...
Also, since you're not using CDN (I think), I would suggest making the template a component with a separate Vue file rather than doing it inside template literals, something like that:
Products.vue
<template>
<div id="products">
<div class="productsItemContainer" v-for="product in products">
<div class="productsItem">
<!-- The rest of the elements -->
</div>
</div>
</div>
</template>
<script>
export default {
name: 'Products',
data() {
return {
products: []
}
},
mounted() {
axios
.get("js/prods.json")
.then(response => {
this.products = response.data.products;
});
}
}
</script>
And then in your main JS file or anywhere else requiring this component:
import Products from './components/Products.vue';
new Vue({
el: '#app',
data() {
return {
//...
}
},
components: {
Products
}
})
<div id="app">
<Products />
</div>

Can't get weather data from opendweathermap using Vue.js

I want to create a simple weather report website using Vue.js, I just learned this framework and had accessed public data before. But this time I am stuck.
There are two versions of methods I have tried to get data.
var app = new Vue({
el: "#weather",
data: {
city: '',
weather:[],
date: new Date().toDateString(),
greeting:''
},
methods: {
//method 1
getData: function () {
var city = this.city
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&lang=en&appid=a495404234abce9b5830b1e8d20e90a6",
function (data) {
console.log(data)
});
},
//method 2
getData: function () {
$("#search").keypress(function (e) {
if (e.which == 13) {
var city = $("#search").val();
if (city != " ") {
var url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&lang=en&appid=a495404234abce9b5830b1e8d20e90a6";
console.log(url);
}
$.getJSON(url, function (data) {
this.weather = data.weather;
console.log(data);
this.returnGreeting();
})
}
})
},
}
}
});
<div class="container" id="weather">
<h1>Weather Pro</h1>
<div class="float-left"><h2>{{date}}</h2></div>
<div class="float-right" ><h3 id="time"></h3></div>
<p>{{greeting}}</p>
<div class="input-group">
<form>
<input v-model="city" class='searchbar transparent' id='search' type='text' placeholder=' enter city' />
<input id='button' #click="getData" type="button" value='GO' />
</form>
</div>
{{city}}
<div class="panel">
<div class="panel-body" v-for="d in data">
<p>
{{data}}
</p>
</div>
<ul class="list-group list-group-flush">
<!-- <li class="list-group-item">{{data.weather[0].main}}</li>
<li class="list-group-item">{{data.weather[0].description}}</li> -->
</ul>
</div>
</div>
<!-- vue -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I got an error :
[Vue warn]: Property or method "data" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
Consider data to be your model. Don't reference data directly in your view, reference properties that are on the model instead.
So instead of <div>{{data.city}}</div> use <div>{{city}}</div>
var app = new Vue({
el: "#weather",
data() {
return {
city: '',
weather: [],
date: new Date().toDateString(),
greeting: ''
};
},
methods: {
getData() {
fetch("http://api.openweathermap.org/data/2.5/weather?q=" + this.city + "&units=metric&lang=en&appid=a495404234abce9b5830b1e8d20e90a6")
.then(res => res.json())
.then(data => {
this.weather = data.weather;
});
}
}
});
<div class="container" id="weather">
<h1>Weather Pro</h1>
<div class="float-left">
<h2>{{date}}</h2>
</div>
<div class="float-right">
<h3 id="time"></h3>
</div>
<p>{{greeting}}</p>
<div class="input-group">
<form>
<input v-model="city" class='searchbar transparent' id='search' type='text' placeholder=' enter city' />
<input id='button' #click="getData" type="button" value='GO' />
</form>
</div>
{{city}}
<div class="panel">
<div class="panel-body" v-for="d in weather">
<p>
{{d}}
</p>
</div>
<ul class="list-group list-group-flush"></ul>
</div>
</div>
<!-- vue -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I found out what caused the issues:
I need to define data in data, as I reference data directly in my html page, but this is optional.
Turns out there is a slim jQuery version from bootstrap that overrides the min jQuery. And $.getJSON() needs min jQuery.
looks like zero beat me to it, but here's a version using jquery call
the issue is, as mentioned in comment, that data.data is not defined. so define data inside data, and assign result to this.data. However, because it's inside a function and the scope changes, you need to store scope using var that = this and use that.data = data to assign result
dom:
<div class="container" id="weather">
<h1>Weather Pro</h1>
<div class="float-left"><h2>{{date}}</h2></div>
<div class="float-right" ><h3 id="time"></h3></div>
<p>{{greeting}}</p>
<div class="input-group">
<form>
<input v-model="city" class='searchbar transparent' id='search' type='text' placeholder=' enter city' />
<input id='button' #click="getData" type="button" value='GO' />
</form>
</div>
{{city}}
<div class="panel">
<div class="panel-body" v-for="d in data">
<p>
{{d}}
</p>
</div>
<ul class="list-group list-group-flush">
</ul>
</div>
</div>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Script:
var app = new Vue({
el: "#weather",
data: {
city: '',
weather:[],
date: new Date().toDateString(),
greeting:'',
data: null,
},
methods: {
//method 1
getData: function () {
var that = this;
var city = this.city
console.log('getData')
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&lang=en&appid=a495404234abce9b5830b1e8d20e90a6",
function (data) {
console.log(data)
that.data = data;
});
},
}
});
Here is an example fiddle.

how to filter post by title using Vue js 2.x directives instead of vue js 1.x

I am learning to use vue js with wprest api by following watch-learn tutorials on the same topic. the problem is that the vue js version used in the tutorial seems to be v 1.x and i started using vue js 2.x. I was able to figure out the initial stages on how to display all the post using vue js 2.x.. I have an input field using which I search for a specific title it should filter and show the post. The issue is unable to workout exactly how it needs to be computed using vuejs 2.x.. I have included a codepen link containing the json data as well as my working code.
the following is the input field to be used to filter the posts by title
<div class="row">
<h4>Filter by name:</h4>
<input type="text" name="" v-model="nameFilter">
</div>
<div class="row">
<div class="col-md-4" v-for="post in posts">
<div class="card post">
<img class="card-img-top" v-bind:src="post.fi_300x180" >
<div class="card-body">
<h2 class="card-text">{{ post.title.rendered }}</h2>
<small class="tags" v-for="category in post.cats">{{ category.name }}</small>
</div>
</div> <!-- .post -->
</div> <!-- .col-md-4 -->
</div> <!-- .row -->
https://codepen.io/dhivyasolomon/pen/LdZKJY
I would appreciate any help in figuring out the next step. thanks.
You don't need directives, achieve this using the power of Computed properties
So you will have to itarate over the computed property which filter the posts by the input value and return a new array of posts.
Little example:
new Vue({
el: '#example',
computed: {
filteredPosts () {
return this.posts.filter(p => p.title.toLowerCase().includes(this.filterText.toLowerCase()))
}
},
data () {
return {
filterText: '',
posts: [
{
title: 'My first post title',
body: 'foo'
},
{
title: 'Another post title',
body: 'foo'
},
{
title: 'This will work fine',
body: 'foo'
},
{
title: 'Omg it\'s working!',
body: 'foo'
}
]
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.js"></script>
<div id="example">
<input type="text" v-model="filterText" />
<ul>
<li v-for="post in filteredPosts">{{ post.title }}</li>
</ul>
</div>

Categories