pixabay api doesnt provide any results - javascript

so im trying to use an api from pixabay website however i do not have any results , the api doesnt send any results i checked it using console.log
i would like to have a little help from you guys
thank you
here is the code using vuejs
so im trying to use an api from pixabay website however i do not have any results , the api doesnt send any results i checked it using console.log
i would like to have a little help from you guys
thank you
here is the code using vuejs
<template>
<section>
<div class="row">
<form class="form-inline d-flex justify-content-center md-form form-sm mt-0">
<i class="fas fa-search" aria-hidden="true"></i>
<input class="form-control form-control-sm ml-3 w-75" type="text" placeholder="Search"
aria-label="Search" v-model="searchText" v-on:keyup.enter.stop.prevent="search">
</form>
</div>
<!-- Grid row -->
<!-- Grid row -->
<div class="gallery" id="gallery">
<!-- Grid column -->
<div class="mb-3 pics" v-for="image in images" :key="image.id" >
<img class="img-fluid" :src="image.largeImageURL" alt="">
</div>
</div>
</section>
</template>
<script>
// # is an alias to /src
import HelloWorld from "#/components/HelloWorld.vue";
import axios from 'axios'
export default {
name: "Home",
components: {
HelloWorld,
},
data () {
return {
searchText: '',
amount: 15,
apiUrl: 'https://pixabay.com/api/',
apiKey: '19405941-132a0646104b54c8459f0746c',
images: []
}
},
mounted () {
},
methods:{
search:function(event){
axios
.get( `${this.apiUrl}?key=${this.apiKey}&q=${this.searchText}`)
.then(response => (this.images = response.data.hits))
console.log(this.images)
}
}
};
</script>
>

Pressing the enter key is submitting your form. The prevent modifier is on the input but should be on the <form>:
<form #submit.prevent>
And it can be removed from your keypress event listener:
v-on:keyup.enter="search"

Related

Vue CLI - TypeError: Cannot read properties of undefined (reading '1')

I'm beginner in VueJS and hoping for your help.
I'm trying to create Weather forecast app based on OpenWeatherMap API.
The concept is such that:
Enter some location to input on homepage and click to search button. (in my code it's a component Search.vue)
Redirecting to another page and show results - current weather and forecast for next 6 days. (component Weather.vue)
I created function with two consistent fetch calls. First fetch taking entered input query and return needed data from Current Weather Data API. After that, function run second fetch to One Call API based on latitude longitude from first fetch.
Everything is working and showing fine, but i don't undestand why i have an error Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '1') in console:
Сan someone know how to fix this error?
My Search.vue (homepage) component:
<template>
<div class="row">
<div class="search-col col">
<div class="search-box">
<input
type="text"
class="search-bar"
placeholder="Location"
v-model="query">
<router-link :to="{name: 'DetailedWeather', params: { query: query }}" class="btn-search">
<i class="fas fa-search"></i>
</router-link>
</div>
</div>
</div>
</template>
My Weather.vue (weather results showing page) component:
<template>
<div class="row" v-if="typeof weather.main != 'undefined'">
<div class="weather-col col">
<div class="weather-app">
<div class="weather-box">
<div class="weather-top-info">
<div class="clouds-level"><span class="icon"><i class="fas fa-cloud"></i></span> {{ weather.clouds.all }}%</div>
<div class="humidity"><span class="icon"><i class="fas fa-tint"></i></span> {{ weather.main.humidity }}%</div>
</div>
<div class="weather-main-info">
<div class="temp-box">
<div class="temp-main">{{ Math.round(weather.main.temp) }}</div>
<div class="temp-inner-box">
<div class="temp-sign">°C</div>
<div class="temp-max"><span class="icon"><i class="fas fa-long-arrow-alt-up"></i></span> {{ Math.round(weather.main.temp_max) }}°</div>
<div class="temp-min"><span class="icon"><i class="fas fa-long-arrow-alt-down"></i></span> {{ Math.round(weather.main.temp_min) }}°</div>
</div>
</div>
<div class="weather-desc">{{ weather.weather[0].description }}</div>
<div class="weather-icon">
<img :src="'http://openweathermap.org/img/wn/'+ weather.weather[0].icon +'#4x.png'">
</div>
</div>
<div class="weather-extra-info">
<div>Feels like: <span>{{ Math.round(weather.main.feels_like) }}°C</span></div>
<div>Sunrise: <span>{{ weather.sys.sunrise }}</span></div>
<div>Sunset: <span>{{ weather.sys.sunset }}</span></div>
</div>
</div>
</div>
</div>
<div class="forecast-col col">
<div class="row">
<div class="forecast-item-col col" v-for="day in forecastDays" :key="day">
<div class="forecast-box">
<div class="forecast-date">{{ forecast.daily[day].dt }}</div>
<div class="forecast-temp">{{ Math.round(forecast.daily[day].temp.day) }}°C</div>
<div class="forecast-icon"><img :src="'http://openweathermap.org/img/wn/'+ forecast.daily[day].weather[0].icon +'#2x.png'"></div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="actions-col col">
<router-link :to="{name: 'Search'}" class="btn btn-default">
Back to search
</router-link>
</div>
</div>
</template>
<script>
export default {
name: 'Weather',
props: ['query'], //getting from homepage
data() {
return {
api_key:'b7fe640e9a244244a6f806f3a6cbf5fc',
url_base:'https://api.openweathermap.org/data/2.5/',
forecastDays: 6,
weather: {},
forecast: {}
}
},
methods: {
fetchWeather(){
// first call
fetch(`${this.url_base}weather?q=${this.query}&units=metric&appid=${this.api_key}`)
.then(response =>{ return response.json() }).then(this.setResults);
},
setResults(results){
this.weather = results;
// consistent second call
fetch(`${this.url_base}onecall?lat=${results.coord.lat}&lon=${results.coord.lon}&exclude=current,minutely,hourly,alerts&units=metric&appid=${this.api_key}`)
.then(data =>{ return data.json() }).then(this.setForecast);
},
setForecast(results){
this.forecast = results
},
},
created() {
this.fetchWeather();
}
</script>
My router/index.js file:
import { createRouter, createWebHashHistory } from 'vue-router'
import Search from '../components/Search.vue'
import Weather from '../components/Weather.vue'
const routes = [
{
path: '/',
name: 'Search',
component: Search
},
{
path: '/detailed-weather',
name: 'DetailedWeather',
component: Weather,
props: true
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
From what I guess (given the code and the error), there might be an issue with the objects you are receiving from the API.
The error message suggests you are trying to read something from an array at a specific index that is undefined.
The only occurrence in your code that could cause this error is from the template, where you are reading, for example:
{{ forecast.daily[day].dt }}
{{ Math.round(forecast.daily[day].temp.day) }}
I can't tell exactly which one is it, but try to double check the shape of the objects you are working with.

cannot get the calendar datepicker to popup - Framework7

I'm making a small app for first time making use of HTML, Javascript and Framework7.
I've installed framework7 and have made the directory and installation of the basic starter
template of files for a blank project...Currently using 'npm start' server, and it returns the default homepage content on the browser. so that's OK...
Right now I only want the 'Calendar/Datepicker' to function. I've gotten the date field to display. But when I try to click it and get the calendar to show, like it does in Framework7 documentation https://v3.framework7.io/docs/calendar.html ,
Nothing comes up. I've now tried multiple times have done just as the guide asked, and there is no response. Is there something extra that I need?
Thanks for any advise.
I've included parts of the code below:
app.js :
import $ from 'dom7'; import Framework7 from 'framework7/bundle';
// Import F7 Styles
import 'framework7/framework7-bundle.css';
// Import Icons and App Custom Styles
import '../css/icons.css'; import '../css/app.css';
// Import Routes
import routes from './routes.js';
// Import Store
import store from './store.js';
// Import main app component
import App from '../app.f7';
var app = new Framework7({
name: 'WeatherStationDat', // App name
theme: 'auto', // Automatic theme detection
el: '#app', // App root element
component: App, // App main component
// App store
store: store,
// App routes
routes: routes,
});
//HERE
var calendar = app.calendar.create({
inputEl: "#calendarinput"
});
home.f7 :
<template>
<div class="page" data-name="home">
<!-- Top Navbar -->
<div class="navbar navbar-large">
<div class="navbar-bg"></div>
<div class="navbar-inner">
<div class="left">
<a href="#" class="link icon-only panel-open" data-panel="left">
<i class="icon f7-icons if-not-md">menu</i>
<i class="icon material-icons if-md">menu</i>
</a>
</div>
<div class="title sliding">WeatherStationDat</div>
<div class="right">
<a href="#" class="link icon-only panel-open" data-panel="right">
<i class="icon f7-icons if-not-md">menu</i>
<i class="icon material-icons if-md">menu</i>
</a>
</div>
<div class="title-large">
<div class="title-large-text">WeatherStationDat</div>
</div>
</div>
</div>
<!-- Toolbar-->
<div class="toolbar toolbar-bottom">
<div class="toolbar-inner">
Left Link
Right Link
</div>
</div>
<!-- Scrollable page content-->
<div class="page-content">
<div class="block block-strong">
<p>Here is your blank Framework7 app. Let's see what we have here.</p>
</div>
<div class="block block-strong">
<p>enter date</p>
<div class="list no-hairlines-md">
<ul>
<li>
<div class="item-content item-input">
<div class="item-inner">
<div class="item-input-wrap">
<!-- HERE -->
<input type="text" placeholder="Your birth date" readonly="readonly" id="calendarinput"/>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</template>
<script>
export default () => {
return $render;
}
</script>
Ok I figured out a way to get it to work. found out how to do it while debugging another field. I had assumed that because 'var app = new Framework7' code was present in app.js, that's where to put the calendar.create() code. But actually when that code is put in section of home.f7 file, inside 'export default' and 'on pageInit', the
calendar pops up.
notice, $f7.calendar.create() is used in this file, not app.calendar.create(). there actually was one documentation that showed that being done, but I missed it before.
The home.f7 file is used here; I tried putting below script code in app.js
but there was no response from the calendar field.
This is the HTTP that goes in the content section of the home.f7 page:
<!--CALENDAR-->
<div class="block block-strong">
<p>ENTER DATE</p>
<div class="list no-hairlines-md">
<ul>
<li>
<div class="item-content item-input">
<div class="item-inner">
<div class="item-input-wrap">
<input type="text" placeholder="Enter date of record" readonly="readonly" id="calendarinput"/>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
At the end of the file there is a section, This code goes in there:
<script>
export default (props, { $, $f7, $on }) => {
$on('pageInit', () => {
let calendarDefault;
calendarDefault = $f7.calendar.create({
inputEl: '#calendarinput',
});
})
return $render;
}
</script>

How to manage re-rendering a navigation on a SPA in vue js

I am building a SPA with the Vue.js framework. Essentially I have a template in App.vue which holds a navigation and then a router-view below it. When the user goes to login, I have a modal which pops up and sends a login request to my API.
The issue I am having is when the user logs in, I am not sure how I can re-render the navigation so that after a user has logged in, the login and register options are hidden. I understand that I could use a v-if="user" type approach, but I am not sure how I can pass back this 'user' variable back from the modal after a login has been made.
App.vue
<template>
<div id="app">
<img alt="Vue logo" src="./assets/head_img.png">
<nav>
<ul>
<li><router-link to="/games">All games</router-link></li>
<li><router-link to="/">Home</router-link></li>
<li><modal-login>Login</modal-login></li>
<li><modal-register>Register</modal-register></li>
<li v-if="user">Logout</li>
</ul>
</nav>
<router-view></router-view>
</div>
</template>
<script>
import ModalLogin from './components/ModalLogin.vue'
import ModalRegister from './components/ModalRegister.vue'
export default {
name: 'app',
components: {
ModalLogin,
ModalRegister
}
}
</script>
Modal Example
<template>
<div>
Register
<modal name="modal-register" #opened="opened">
<form #submit.prevent="doRegister">
<div class="form-group">
<label for="email" class="block">Email</label>
<input v-model="email" type="email" id="email" name="email" class="border" ref="email">
</div>
<div class="form-group">
<label for="password" class="block">Password</label>
<input v-model="password" type="password" id="password" name="password" class="border">
</div>
<div class="form-group">
<button type="submit">Register</button>
</div>
</form>
<div class="form-group">
<p>Already have an account? Login</p>
</div>
</modal>
</div>
</template>
In my request I have a .then after the request so I can check that the request was a 201 status.
I would appreciate any help into what I could try or what I should be looking at to achieve this type of task.
You need to set the user authentication status globally. Vuex can be used for this purpose.
Example code
const state = {
isAuth: false
}
const mutations ={
setAuth:(state,value)=>state.isAuth = value
}
const actions = {
loginRequest:function({commit}){
// perform login request
commit('setAuth',true); // call this after you get the login response
}
}
Inside the component add a computed function
computed:{
isAuth:function(){
return this.$store.state.isAuth;
}
}
Now isAuth can use for handling the condition to hide the sections you need.

How to load Html layout into vuejs component?

I am using Vuejs cdn. In which I have a Navigation menu. I want to load different layout when a user clicks on Nav menu.
for example
<div class="row" id="mytemplate">
<div class="col-sm-3 sidebar-col">
<div>
<nav class="settings-sidebar">
<h4>Profile settings</h4>
<ul>
<li class="active" v-on:click="Profile()">
<a >Profile picture</a>
</li>
<li class="" v-on:click="Business()">
<a >Business details</a>
</li>
<li class="" v-on:click="Equipments()">
<a >Equipments details</a>
</li>
</ul>
</nav>
</div>
</div>
<div class="col-sm-9 col-xs-12 settings-body">
{{ load_layout_here }}
</div>
Now when user click on "Business Details" option it should run function Business() and load layout from business.html or business.php
the sample code in business.php
<div class="form">
<div class="input-field">
<h5>Business name</h5>
<input type="text" class="textbox" name="primary-phone" value="Perfect choice movers" placeholder="Your business name" maxlength="15">
</div>
<div class="input-field inline-input">
<h5>City</h5>
<input type="text" class="textbox " name="business-city" value="myCity" placeholder="Business address" maxlength="15">
</div>
<button class="btn btn-orange" type="submit">Save</button>
My vue.js code is
var app2 = new Vue({
el: '#mytemplate',
data : {
message : 'hi',
},
methods: {
Profile : function () {
this.message = 'Profile';
},
Business : function () {
// Here I want to call Html Template to load seprate layout
this.message = 'Business';
},
Equipments : function () {
this.message = 'Equipments';
}
}
})
I have seen lots of answers on the internet but they all using vue template engine or .vue files. Which I do not want to use
Note : I am using CodeIgniter as PHP framework. and Vue for frontend.
You can use axios to render the html. What ever data come in response data variable. That should to show.
Profile : function () {
axios.get('profile.php')
.then(function (response) {
console.log(response.data);
// response
this.message = response.data.json;
})
.catch(function (error) {
// handle error
console.log(error);
});
}
and to use axios, you have to include cdn file.
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Vue js template rendering issue

First time with vue. I am learning it playing around with some examples from Laracasts. I cannot get external template to render and the console shows cannot find element: #toolbar-chat.
My template is:
<template>
<div id="toolbar-chat">
<div class="toolbar-chat">
<ul v-for="chat in messages">
<li><b>#{{ chat.nickname }} says:</b> #{{ chat.message }}</li>
</ul>
</div>
<div class="input-group input-group-sm">
<input class="form-control" value="" placeholder="Type message..." required="required" maxlength="140" v-model="newMsg">
<div class="input-group-btn">
<button class="btn btn-primary" type="button" #click="press">
<i class="fa fa-paper-plane"></i>
</button>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
console.log('Component mounted.')
},
data() {
return {
nickname: [],
message: ''
}
},
ready() {
Echo.channel(chat_channel)
.listen('ChatMessageWasReceived', (data) => {
// Push data to messages list.
this.messages.push({
message: data.chat.message,
nickname: data.player.nickname
});
});
},
methods: {
press() {
// Send message to backend.
this.$http.post(chat_send_route, {message: this.newMsg})
.then((response) => {
// Clear input field.
this.newMsg = '';
});
}
}
};
</script>
My HTML contains the following tag:
<div class="col-xs-12 col-md-4" id="toolbarChat">
<my-chat></my-chat>
</div>
My vue component call is inside a document ready function like this:
require('./../app/bootstrap');
$(document).ready(function()
{
....
// Set up chat
Vue.component('my-chat', require('./../generic/chat.vue'));
const app = new Vue({
el: '#toolbar-chat'
});
});
And I include vue in my bootstrap file like this, then compile with webpack and no errors.
window.Vue = require('vue');
Why is my HTML template not rendering?
In your HTML you have the following div:
<div class="col-xs-12 col-md-4" id="toolbarChat">
<my-chat></my-chat>
</div>
Change it to
<div class="col-xs-12 col-md-4" id="toolbar-chat">
<my-chat></my-chat>
</div>
Because that is the id that new Vue({el: "#toolbar-chat",...}) is looking for.

Categories

Resources