I’m using Vue to create a Flickr app and want to add a search bar so users can search for photos containing tags with their search term.
What i’ve done so far produces some results, but I noticed the photos don’t always include my search term as tags, for example if I search 'cats' the returned items might have the tags 'cat' but not 'cats' and sometimes it doesn't include tags that are even slightly similar.
There's no console errors, so i'm not sure where to find the error.
<template>
<b-container>
<b-row>
<b-col md="12">
<b-input-group size="lg" prepend="Search" class="flickr-search">
<b-form-input v-model="search"></b-form-input>
</b-input-group>
</b-col>
</b-row>
<b-row>
<b-card-group columns>
<b-col v-for="photo in Photos" class="item" md="12">
<b-card :title="photo.title"
:img-src="photo.media.m"
img-alt="Image"
img-top
img-fluid
tag="article"
style="max-width: 20rem;"
class="mb-2">
<span class="item-date">31 May 2017</span>
<hr/>
<p>By <a :href="'https://www.flickr.com/photos/' + photo.author_id" :title="formatAuthor(photo.author)" target="_blank">{{ formatAuthor(photo.author) }}</a></p>
<ul class="tags">
<li v-for="tag in splitTags(photo.tags)" class="item-tag">
<a :href="'https://www.flickr.com/photos/tags/' + tag" target="_blank" class="item-taglink">{{ tag }}</a>
</li>
</ul>
</b-card>
</b-col>
</b-card-group>
</b-row>
</b-container>
</template>
<script>
import jsonp from "jsonp";
export default {
name: 'PhotoFeed',
data: function () {
return {
Photos: [],
apiURL: "https://api.flickr.com/services/feeds/photos_public.gne?format=json",
search: ''
}
},
mounted(){
this.getFlickrFeed();
},
methods: {
getFlickrFeed(){
let jsonp = require('jsonp');
let self = this;
jsonp(this.apiURL, {name: 'jsonFlickrFeed'}, (err, data) => {
if (err) {
console.log(err.message);
}
else {
self.Photos = data.items;
}
})
},
formatAuthor(authorString){
if (authorString) return authorString.split("\"")[1];
return "Author";
},
splitTags(tagsString) {
if (tagsString) return tagsString.split(" ");
}
},
watch: {
search(newVal, oldVal) {
let self = this;
let apiURL = "https://api.flickr.com/services/feeds/photos_public.gne?tags=" + self.search + "&format=json";
let jsonp = require('jsonp');
jsonp(apiURL, {name: 'jsonFlickrFeed'}, (err, data) => {
if (err) {
console.log(err.message);
}
else {
self.Photos = data.items;
}
})
}
}
}
</script>
An error won't be thrown if the flicker API doesn't return any results.
In the UI you can let you users know they can provide a comma separated list of keywords, example cats, cat
You can also check no see if there are any results and display a message if none were found here is just one simple example implementation:
Relevant HTML
<b-card-group columns v-if="Photos.length">
<b-col v-for="photo in Photos" class="item" md="12">
<b-card :title="photo.title"
:img-src="photo.media.m"
img-alt="Image"
img-top
img-fluid
tag="article"
style="max-width: 20rem;"
class="mb-2">
<span class="item-date">31 May 2017</span>
<hr/>
<p>By <a :href="'https://www.flickr.com/photos/' + photo.author_id" :title="formatAuthor(photo.author)" target="_blank">{{ formatAuthor(photo.author) }}</a></p>
<ul class="tags">
<li v-for="tag in splitTags(photo.tags)" class="item-tag">
<a :href="'https://www.flickr.com/photos/tags/' + tag" target="_blank" class="item-taglink">{{ tag }}</a>
</li>
</ul>
</b-card>
</b-col>
</b-card-group>
<b-col md="12" v-else-if="!Photos.length && errorMessage">
<p>{{errorMessage}}</p>
</b-col>
Relevant JS
data: function () {
return {
Photos: [],
apiURL: "https://api.flickr.com/services/feeds/photos_public.gne?format=json",
search: '',
errorMessage: null
}
}
In both getFlickerFeed & watch: search:
if (err) {
self.errorMessage = err.message;
}
else {
self.Photos = data.items;
if (self.Photos.length) {
self.errorMessage = null;
} else {
self.errorMessage = 'No results found for: ' + self.search
}
}
Related
I have pretty simple table of users here with only 4 cols, and i want to show a button for each user depending on his status 'isActive'. If user is active i want to show button with text 'disable' and vice versa. I am little bit stuck with this because i dont have an idea how can i show these buttons, because i am using vuexy template for this project(admin panel). Is there a way to do this with JSX?
Please take a look at code, i am getting data from mysql with nodejs. Ask me if you need more info. Thanks.
<template>
<div>
<div class="container">
<b-card-text class="mb-2">
<div
v-if="showLoginError"
class="text-center bg-danger colors-container rounded text-white width-360 height-50 d-flex align-items-center justify-content-center mr-1 ml-50 my-1 shadow"
>
<span>{{ loginError }}</span>
</div>
</b-card-text>
<b-card-text class="mb-2">
<div
v-if="showSuccessMessage"
class="text-center bg-success colors-container rounded text-white width-360 height-50 d-flex align-items-center justify-content-center mr-1 ml-50 my-1 shadow"
>
<span>{{ successMessage }}</span>
</div>
</b-card-text>
<section id="card-actions" class="input-section">
<b-row>
<b-col cols="8">
<b-card-actions ref="cardAction">
<validation-observer ref="simpleRules">
<b-form>
<b-row>
<b-col md="6">
<b-form-group>
<validation-provider
#default="{ errors }"
name="First Name"
rules="required"
>
<b-form-input
v-model="name"
:state="errors.length > 0 ? false:null"
placeholder="Twitter username"
/>
</validation-provider>
</b-form-group>
</b-col>
<b-col cols="12">
<b-button
variant="primary"
type="submit"
#click.prevent="validationForm"
>
Submit
</b-button>
</b-col>
</b-row>
</b-form>
</validation-observer>
</b-card-actions>
</b-col>
</b-row>
</section>
// This is table
<b-table responsive="sm" :items="items"/>
</div>
</div>
</template>
<script>
import { ValidationProvider, ValidationObserver } from 'vee-validate'
import {
BFormInput, BFormGroup, BForm, BRow, BCol, BButton, BTable,
} from 'bootstrap-vue'
import { required } from '#validations'
import axios from 'axios'
import { getUserToken } from '#/auth/auth'
export default {
components: {
ValidationProvider,
ValidationObserver,
BFormInput,
BFormGroup,
BForm,
BRow,
BCol,
BButton,
BTable,
},
data() {
return {
name: '',
successMessage: '',
showSuccessMessage: false,
loginError: '',
showLoginError: false,
required,
items: [],
}
},
beforeMount() {
this.getAllUsers()
},
methods: {
getAllUsers() {
const API_URL = `${this.$server}/api/twitter/allusers`
const params = {
token: getUserToken(),
}
axios.post(API_URL, null, { params }).then(res => {
if (res.data) {
res.data.forEach(element => {
let isActive = 'active'
if (element.isActive === 0) {
isActive = 'disabled'
}
const arr = {
twitter_name: element.twitter_name,
twitter_username: element.twitter_username,
twitter_id: element.twitter_id,
userActive: isActive,
}
this.items.push(arr)
})
}
})
},
validationForm() {
const API_URL = `${this.$server}/api/twitter/adduser`
const params = {
twitter_username: this.name,
token: getUserToken(),
}
axios.post(API_URL, null, { params }).then(res => {
if (res.data.success) {
this.successMessage = res.data.message
this.showSuccessMessage = true
// Hide message after 5sec
setTimeout(() => {
this.successMessage = ''
this.showSuccessMessage = false
}, 5000)
} else {
this.loginError = res.data.message
this.showLoginError = true
// Hide message after 5sec
setTimeout(() => {
this.loginError = ''
this.showLoginError = false
}, 5000)
}
})
},
},
}
</script>
I'm a little bit confused, where do you want to show your button ?
If it's in the table, you can use the custom templation of Bootstrap-Vue, you'll find the doc here with an example : https://bootstrap-vue.org/docs/components/table#custom-data-rendering
EDIT: here an example for your case
<b-table responsive="sm" :items="items">
<template #cell(userActive)="data">
<b-button v-if="data.userActive">Disabled</b-button>
<b-button v-else>Enabled</b-button>
</template>
</b-table>
There is a component in which two select fields (country, city) are created on click.The fields are dependent, when the country is selected, the values in the second select (city) are changed.The problem is that when we change one select (country) all other select-s (cities) change.
<template>
<b-container class="bv-example-row">
<b-row v-for="(station, counter) in stations" v-bind:key="counter">
<b-col cols="6">
<label>Country</label>
<select class='form-control' name="country_dest_id" v-model='station.country' #change='getStates($event)'>
<option value='0' >Select Country</option>
<option v-for='data in countries' :value='data.id'>{{ data.name }}</option>
</select>
</b-col>
<b-col cols="6">
<label >City</label>
<select class='form-control' v-model='station.state'>
<option value='0' >Select State</option>
<option v-for='data in states' :value='data.id'>{{ data.name }}</option>
</select>
</b-col>
<b-col cols="1">
<button class="btn btn-danger remove" #click="deleteStation(counter)"><i class="fa fa-times" aria-hidden="true"></i> Remove</button>
</b-col>
</b-row>
<b-row class="justify-content-md-center">
<b-col cols="3" md="3">
<button class="btn btn-success" type="button" #click="addStation">Add</button>
</b-col>
</b-row>
</b-container>
</template>
<script>
export default {
mounted() {
console.log('Component mounted.')
},
data(){
return {
stations:[
{
country: '',
state:'',
}
],
countries: [],
states:[]
}
},
methods:{
addStation(){
this.stations.push({
country:'',
state: ''
})
},
deleteStation(counter){
this.stations.splice(counter,1);
},
getCountries: function(){
axios.get('/getCountries')
.then(function (response) {
this.countries = response.data;
}.bind(this));
},
getStates: function(event) {
console.log(event.target.value);
axios.get('/getStates',{
params: {
country_id: event.target.value
}
}).then(function(response){
this.states = response.data;
}.bind(this));
}
},
created: function(){
this.getCountries()
}
}
</script>
How to make field groups unique values?
The problem is that the getStates function works always on the same array in data(). #change overwrites that value & every select that is bound to it receives the new set of values.
You'd be better off if you built up an object of states, something like (the sample probably is not working, just giving an idea):
data() {
return {
states: {
countryId1: ["cid1state1", "cid1state2"],
countryId2: ["cid2state1", "cid2state2"],
},
}
},
methods: {
getStates: function(event) {
if (!(event.target.value in this.states)) {
axios.get('/getStates',{
params: {
country_id: event.target.value
}
}).then(function(response){
this.states[event.target.value] = response.data;
}.bind(this));
}
}
},
I try to create a method that let the user to insert just value that exists in database, like an autocomplete.
Right now returns a list, but that list is not sorted, doesn't matter what I type the data from the list are the same.
<b-form-group label="Name" label-for="name-input">
<b-form-input
id="name-input"
v-model="query"
#keyup="autoComplete"
></b-form-input>
<div v-if="results.length">
<ul>
<li class="list-group-item" v-for="(result, index) in results" :key="index" id="display-none" #click="suggestionClick(result.name)">
{{ result.name }}
</li>
</ul>
</div>
</b-form-group>
autoComplete() {
this.results = [];
if (this.query.length > 2) {
get("/datafromapi", {
params: {
q: this.query
}
}).then(response => {
this.results = response.data.data;
});
}
},
suggestionClick(index) {
this.query = index
var element = document.getElementById("display-none");
element.classList.add("display-none");
},
I'm passing a collection of locations into vue-carousel. I'm using the same collection in a couple of other places on the page, emitting the selected location to the root, which is where the locations and selected location are stored, in an eventHub.
The tricky part was getting the carousel to move to the right page - I'm showing three locations at a time in larger viewports and just one on smaller, using the perPageCustom option. I create keys in the api in laravel and based on the size of the window, I'm moving to the right page and it all works, but when it loads I get an error because the ref doesn't exist when the watcher first fires off. I know that's the issue, but I'm not sure how to have a watcher for when the location changes, that doesn't watch when the page loads... perhaps using the mount?
My component:
<template>
<div>
<h3>Locations ({{locations.length}})</h3>
<p class="lead">Serving California in the greater Sacramento and Los Angeles areas.</p>
<carousel v-if="locations.length > 0" ref="locations-carousel" :scrollPerPage="true" :perPage="1" :perPageCustom="[[480, 1], [768, 3]]" v-on:pageChange="pageChange">
<slide v-for="loc in locations" :key="loc.id">
<div class="card" style="width: 18rem;" v-bind:class="{ closest: loc.is_closest, active: loc.id == location.id }">
<img v-on:click="changeLocation(loc.id)" v-if="loc.is_comingsoon === 0" class="card-img-top" :src="'/assets/images/location_'+loc.pathname+'.jpg'" alt="Card image cap">
<img v-on:click="changeLocation(loc.id)" v-if="loc.is_comingsoon === 1" class="card-img-top" :src="'/assets/images/coming-soon.png'" alt="Card image cap">
<div class="card-body">
<h5 class="card-title" v-on:click="changeLocation(loc.id)">{{ loc.name }}</h5>
<p class="card-text">{{ loc.address }}<br>{{ loc.city_name }}<br>{{ loc.phone | phone }}</p>
<div class="btn-group" role="group" aria-label="Location Buttons">
<a class="btn btn-outline btn-default" :href="'tel:'+ loc.phone"><font-awesome-icon icon="phone"></font-awesome-icon> call</a>
<a class="btn btn-outline btn-default" :href="loc.map"><font-awesome-icon icon="globe"></font-awesome-icon> map</a>
<a class="btn btn-outline btn-default" v-on:click="changeLocation(loc)" v-bind:class="{ active: loc.id == location.id }"><font-awesome-icon icon="star"></font-awesome-icon> pick</a>
</div>
<p class="card-text">{{ loc.note }}</p>
<span class="badge badge-closest" v-if="loc.is_closest"><font-awesome-icon icon="map-marker"></font-awesome-icon> closest detected</span>
<span class="badge badge-active" v-if="loc.id == location.id"><font-awesome-icon icon="star"></font-awesome-icon> selected <font-awesome-icon icon="angle-double-down" :style="{ color: 'white' }"></font-awesome-icon></span>
</div>
</div>
</slide>
</carousel>
<font-awesome-icon icon="spinner" size="lg" v-if="locations.length < 1"></font-awesome-icon>
</div>
</template>
<script>
Vue.filter('phone', function (phone) {
return phone.replace(/[^0-9]/g, '')
.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
});
import { Carousel, Slide } from 'vue-carousel';
var axios = require("axios");
export default {
name: 'locations-carousel',
props: ['location', 'pg', 'locations'],
components: {
Carousel,
Slide
},
data() {
return {
debounce: null,
subs: {},
clear: 0
};
},
watch: {
location: function(newVal, oldVal) { // watch it
console.log('Prop changed: ', newVal, ' | was: ', oldVal)
console.log('key: '+this.location.key);
if( window.innerWidth > 481 ) {
if( this.location.pg == 1 ) {
this.$refs['locations-carousel'].goToPage(-0);
} else {
this.$refs['locations-carousel'].goToPage(1);
}
} else {
this.$refs['locations-carousel'].goToPage(this.location.key);
}
}
},
methods: {
pageChange(i){
console.log('current Index', i);
},
changeLocation(location) {
this.$eventHub.$emit('location-loaded', location);
}
}
}
</script>
The error I'm getting:
[Vue warn]: Error in callback for watcher "location": "TypeError:
Cannot read property 'goToPage' of undefined"
found in
---> <LocationsCarousel> at resources/assets/js/components/LocationsCarousel.vue
<Root>
TypeError: Cannot read property 'goToPage' of undefined
at VueComponent.location (app.js?v=0.1:53288)
at Watcher.run (app.js?v=0.1:3937)
at flushSchedulerQueue (app.js?v=0.1:3685)
at Array.<anonymous> (app.js?v=0.1:2541)
at flushCallbacks (app.js?v=0.1:2462)
Perhaps you can check first to see if this.$refs['locations-carousel'] exists before accessing its properties/methods ..
watch: {
location: function(newVal, oldVal) { // watch it
console.log('Prop changed: ', newVal, ' | was: ', oldVal)
console.log('key: ' + this.location.key);
const locationsCarousel = this.$refs['locations-carousel']
if (window.innerWidth > 481) {
if (this.location.pg == 1) {
locationsCarousel && locationsCarousel.goToPage(-0);
} else {
locationsCarousel && locationsCarousel.goToPage(1);
}
} else {
locationsCarousel && locationsCarousel.goToPage(this.location.key);
}
}
},
I have a web page that displays items. For each items there is a button (vuejs component) which allow user to toggle (add/remove) this item to his collection.
Here is the component:
<template lang="html">
<button type="button" #click="toggle" name="button" class="btn" :class="{'btn-danger': dAdded, 'btn-primary': !dAdded}">{{ dText }}</button>
</template>
<script>
export default {
props: {
added: Boolean,
text: String,
id: Number,
},
data() {
return {
dAdded: this.added,
dText: this.text,
dId: this.id
}
},
watch: {
added: function(newVal, oldVal) { // watch it
this.dAdded = this.added
},
text: function(newVal, oldVal) { // watch it
this.dText = this.text
},
id: function(newVal, oldVal) { // watch it
this.dId = this.id
}
},
methods: {
toggle: function(event) {
axios.post(route('frontend.user.profile.pop.toggle', {
pop_id: this.dId
}))
.then(response => {
this.dText = response.data.message
let success = response.data.success
this.dText = response.data.new_text
if (success) {
this.dAdded = success.attached.length
let cardPop = document.getElementById('card-pop-'+this.dId);
if(cardPop)
cardPop.classList.toggle('owned')
}
})
.catch(e => {
console.log(e)
})
}
}
}
</script>
For each item, the user can also open a modal, loaded by a click on this link:
<a href="#" data-toggle="modal" data-target="#popModal" #click="id = {{$pop->id}}">
<figure>
<img class="card-img-top" src="{{ URL::asset($pop->img_path) }}" alt="Card image cap">
</figure>
</a>
The modal is also a Vuejs component:
<template>
<section id="pop" class="h-100">
<div class="card">
<div class="container-fluid">
<div class="row">
<div class="col-12 col-lg-1 flex-column others d-none d-xl-block">
<div class="row flex-column h-100">
<div v-for="other_pop in pop.other_pops" class="col">
<a :href="route('frontend.pop.collection.detail', {collection: pop.collection.slug, pop: other_pop.slug})">
<img :src="other_pop.img_path" :alt="'{{ other_pop.name }}'" class="img-fluid">
</a>
</div>
<div class="col active order-3">
<img :src="pop.img_path" :alt="pop.name" class="img-fluid">
</div>
</div>
</div>
<div class="col-12 col-lg-6 content text-center">
<div class="row">
<div class="col-12">
<img :src="pop.img_path" :alt="pop.name" class="img-fluid">
</div>
<div class="col-6 text-right">
<toggle-pop :id="pop.id" :added="pop.in_user_collection" :text="pop.in_user_collection ? 'Supprimer' : 'Ajouter'"></toggle-pop>
</div>
<div class="col-6 text-left">
<!-- <btnaddpopwhishlist :pop_id="propid" :added="pop.in_user_whishlist" :text="pop.in_user_whishlist ? 'Supprimer' : 'Ajouter'"></btnaddpopwhishlist> -->
</div>
</div>
</div>
<div class="col-12 col-lg-5 infos">
<div class="header">
<h1 class="h-100">{{ pop.name }}</h1>
</div>
<div class="card yellow">
<div class="card p-0">
<div class="container-fluid">
<div class="row">
<div class="col-3 py-2">
</div>
<div class="col-6 py-2 bg-lightgray">
<h4>Collection:</h4>
<h3>{{ pop.collection ? pop.collection.name : '' }}</h3>
</div>
<div class="col-3 py-2 bg-lightgray text-center">
<a :href="route('frontend.index') + 'collections/' + pop.collection.slug" class="btn-round right white"></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</template>
<script>
export default {
props: {
id: Number
},
data() {
return {
pop: {
collection: {
}
}
}
},
ready: function() {
if (this.propid != -1)
this.fetchData()
},
watch: {
id: function(newVal, oldVal) { // watch it
// console.log('Prop changed: ', newVal, ' | was: ', oldVal)
this.fetchData()
}
},
computed: {
imgSrc: function() {
if (this.pop.img_path)
return 'storage/images/pops/' + this.pop.img_path
else
return ''
}
},
methods: {
fetchData() {
axios.get(route('frontend.api.v1.pops.show', this.id))
.then(response => {
// JSON responses are automatically parsed.
// console.log(response.data.data.collection)
this.pop = response.data.data
})
.catch(e => {
this.errors.push(e)
})
// console.log('fetchData')
}
}
}
</script>
Here is my app.js script :
window.Vue = require('vue');
Vue.component('pop-modal', require('./components/PopModal.vue'));
Vue.component('toggle-pop', require('./components/TogglePop.vue'));
const app = new Vue({
el: '#app',
props: {
id: Number
}
});
I would like to sync the states of the component named toggle-pop, how can I achieve this ? One is rendered by Blade template (laravel) and the other one by pop-modal component. But they are just the same, displayed at different places.
Thanks.
You could pass a state object as a property to the toggle-pop components. They could use this property to store/modify their state. In this way you can have multiple sets of components sharing state.
Your component could become:
<template lang="html">
<button type="button" #click="toggle" name="button" class="btn" :class="{'btn-danger': sstate.added, 'btn-primary': !sstate.added}">{{ sstate.text }}</button>
</template>
<script>
export default {
props: {
sstate: {
type: Object,
default: function() {
return { added: false, text: "", id: -1 };
}
}
},
data() {
return {};
},
methods: {
toggle: function(event) {
axios.post(route('frontend.user.profile.pop.toggle', {
pop_id: this.sstate.id
}))
.then(response => {
this.sstate.text = response.data.message
let success = response.data.success
this.sstate.text = response.data.new_text
if (success) {
this.sstate.ddded = success.attached.length
let cardPop = document.getElementById('card-pop-'+this.sstate.id);
if(cardPop)
cardPop.classList.toggle('owned')
}
})
.catch(e => {
console.log(e)
})
}
};
</script>
Live demo
https://codesandbox.io/s/vq8r33o1w7
If you are 100% sure that all toggle-pop components should always have the same state, you can choose to not define data as a function. Just declare it as an object.
data: {
dAdded: this.added,
dText: this.text,
dId: this.id
}
In https://v2.vuejs.org/v2/guide/components.html#data-Must-Be-a-Function, it mentions
a component’s data option must be a function, so that each instance
can maintain an independent copy of the returned data object
If Vue didn’t have this rule, clicking on one button would affect the
data of all other instances
Since you want to sync the data of all toggle-pop component instances, you don't have to follow the data option must be a function rule.