Vuejs

Subscribe to Vuejs feed
most recent 30 from stackoverflow.com 2017-09-14T21:10:11Z
Updated: 7 years 1 week ago

Vue.js clearing data after if is evaluated

Mon, 2017-09-11 14:42

I am making a multi-step form in Rails 5 with Vue.js. I noticed that when a v-if is re-evaluated, the text in the input field gets cleared out. Is there a way to persist the info through the form steps and through other v-if evaluations?

Here's what my form looks like:

<fieldset class="listing-step" v-if="activeStep === 0"> <h2>Basics</h2> <input type='button' value="Next" name='next' @click="activeStep++" :disabled="activeStep === stepList.length - 1" class="btn btn-secondary" /> <div class="row"> <div class="col"> <div class="form-group"> <strong><%= f.label :name %></strong><br> <%= f.text_field :name, class: 'form-control' %> </div> </div> </div> </fieldset> <fieldset class="listing-step" v-if="activeStep === 1"> <h2>Location</h2> <input type='button' value="Previous" name='prev' @click="activeStep--" :disabled="activeStep === 0" class="btn btn-secondary" /> <input type='button' value="Next" name='next' @click="activeStep++" :disabled="activeStep === stepList.length - 1" class="btn btn-secondary" /> <div class="row"> <div class="col"> <div class="form-check"> <label class="form-check-label"> <input class="form-check-input" type="radio" name="map_search" id="map_search_address" value="address" v-on:click="by_address = true" checked> Set by address </label> </div> <div class="form-check"> <label class="form-check-label"> <input class="form-check-input" type="radio" name="map_search" id="map_search_coords" value="coords" v-on:click="by_address = false"> Set by coordinates </label> </div> </div> </div> <div id="listing-location"> <transition name="fade"> <fieldset id="listing-location-child" name="address" v-if="by_address"> <div class="row"> <div class="col"> <div class="form-group"> <strong><%= f.label :city %></strong><br> <%= f.text_field :city, class: 'form-control', 'v-bind:readonly': '!by_address' %> </div> </div> <div class="col"> <div class="form-group"> <strong><%= f.label :state %></strong><br> <%= f.text_field :state, class: 'form-control', 'v-bind:readonly': '!by_address' %> </div> </div> </div> <div class="row"> <div class="col"> <div class="form-group"> <strong><%= f.label :address %></strong><br> <%= f.text_field :address, class: 'form-control', 'v-bind:readonly': '!by_address' %> </div> </div> </div> </fieldset> </transition> <transition name="fade"> <fieldset id="listing-location-child" name="coords" v-if="!by_address"> <div class="row"> <div class="col"> <div class="form-group"> <strong><%= f.label :lat, 'Latitude' %></strong><br> <%= f.number_field :lat, in: -90.0..90.0, step: :any, class: 'form-control', 'v-bind:readonly': 'by_address' %> </div> </div> <div class="col"> <div class="form-group"> <strong><%= f.label :lng, 'Longitude' %></strong><br> <%= f.number_field :lng, in: -180.0..180.0, step: :any, class: 'form-control', 'v-bind:readonly': 'by_address' %> </div> </div> </div> </fieldset> </transition> </div> </fieldset> <fieldset class="listing-step" v-if="activeStep === 2"> <h2>Amenities</h2> <input type='button' value="Previous" name='prev' @click="activeStep--" :disabled="activeStep === 0" class="btn btn-secondary" /> <input type='button' value="Next" name='next' @click="activeStep++" :disabled="activeStep === stepList.length - 1" class="btn btn-secondary" /> <div class="row"> <div class="col"> <div class="form-group"> <strong>Amenities</strong><br> ... </div> </div> </div> </fieldset> <fieldset class="listing-step" v-if="activeStep === 3"> <h2>Images</h2> <input type='button' value="Previous" name='prev' @click="activeStep--" :disabled="activeStep === 0" class="btn btn-secondary" /> <div class="row"> <div class="col"> <div class="form-group"> <strong>Images</strong><br> ... </div> </div> </div> <div class="row"> <div class="col"> <div class="actions"> <%= f.submit class: 'btn btn-success' %> </div> </div> </div> </fieldset>

and my Vue initialization:

const progress = new Vue({ el: '#vue-listing', data: { activeStep: 0, by_address: true, stepList: [ {id: 0, text: 'Basics'}, {id: 1, text: 'Location'}, {id: 2, text: 'Amenities'}, {id: 3, text: 'Images'} ] } })

Thanks in advance!

Categories: Software

Fetching data from api before render component

Mon, 2017-09-11 14:20

I'm sending 2 api requests before render the page:

const Profile = { template: '#profile', attributes: null, photos: [], data: function () { return {attributes: Profile.attributes, photos: Profile.photos}; }, beforeRouteEnter: function (to, from, next) { function getProfile() { return axios.get('user/get-profile?access-token=1', {responseType: 'json'}); } function getPhotos() { return axios.get('photos?access-token=1', {responseType: 'json'}); } axios.all([getProfile(), getPhotos()]) .then(axios.spread(function (profile, memes) { console.log(profile, memes); next(vm => { vm.setProfile(profile); vm.setPhotos(photos); }) })); }, methods: { setProfile: function (response) { Profile.attributes = response.data; console.log(Profile.attributes); }, setPhotos: function (response) { Profile.photos = response.data; console.log(response); }, } };

The problem is rendering occures before setProfile and setPhotos methods. How to correct render my component?

Categories: Software

Karma unit test Vue.js + Foundation

Mon, 2017-09-11 13:22

I'm attempting to add Foundation for Sites to my first Vue.js project that is setup with the Vue CLI.

The website runs however the Karma+Phantomjs unit test suite is emitting this error:

PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR SyntaxError: Invalid character: '`' at webpack:///~/foundation-sites/js/foundation.util.core.js:24:0 <- index.js:10362

I believe this is related to webpack and

Here's an overview of the code changes I've made...

Main.js

import jQuery from 'jquery' window.jQuery = jQuery window.$ = jQuery import Foundation from 'foundation-sites' window.Foundation = Foundation

Hello.vue

<template> ... </template> <script> export default { name: 'hello', mounted () { this.dropdownMenu = new Foundation.DropdownMenu($('#dropdown-menu'), { // These options can be declarative using the data attributes hoverDelay: 300 }) }, data () { return { msg: 'Welcome to Your Vue.js App' } }, destroyed () { this.dropdownMenu.destroy() } } </script>

test/unit/index.js

import Vue from 'vue' import Foundation from 'foundation-sites' window.Foundation = Foundation // ... auto-generated unit tests
Categories: Software

Vue.js close modal from child component

Mon, 2017-09-11 12:54

I want to close vuejs modal from child component inside this modal. Case:

<modal name="some-modal"> <some-component></some-component> </modal>

Inside SomeComponent i want to close some-modal. Is it good approach ? Can it be done better way ? Please adivse, Regards

Categories: Software

Virtual Box Ubuntu, Laravel backend api, Vue frontend - can't connect Vue to Laravel api url

Mon, 2017-09-11 12:38

I have VirtualBox Machine on windows 10, I have Laravel backend api, and Vue for frontend. Now when I run Vue with npm run dev, it starts my Vue app on localhost port 8080, and my Laravel app is on vue.dev/api/quote (this is for post url)

I am using axios and when in my axios.post put my laravel url, I am getting errors in the browser console.

axios.post('http://vue.dev/api/quote', {content: this.quoteContent}) .then( (response) => console.log(response) ) .catch( (error) => console.log(error) );

I can access on ubuntu laravel url and it works. Cant find where is a problem in vue, because when i hit submit button on vue app, I just keep getting error.

enter image description here

Categories: Software

Vuejs eventbus triggers multiple times due to webpack import outport?

Mon, 2017-09-11 12:30

In a vuejs project I use the vue eventbus like this. Emitting this event:

icontag.addEventListener('click', testFunction, false) function testFunction () { console.log('click1') Events.$emit('click2') }

And receiving it in another module I get as output one click1, but multiple click2's. It looks very much like every time there is some code which requires webpack import/ export it triggers an additional result on the eventbus of the same event..., or something..., since in chrome devtools the related code close to the click2's has code like __WEBPACK_IMPORTED_MODULE_5__util nearby.

Any idea what is going on?

Categories: Software

Custom vue events not working

Mon, 2017-09-11 12:00

I am trying to catch vue.js custom event within one component, but it's not catching. What's the problem?

myEventFunc: function() { this.myEvent = true; }, clickedFunc: function() { this.clicked = true; this.$emit('myevent'); }

JSFiddle Example: https://jsfiddle.net/ucean0rh/1/

Categories: Software

How to pass data from one component to other in vue js?

Mon, 2017-09-11 11:55

I am learning vue+laravel. I want to pass value from one component to other component? I have used vue router for routing.

Here is the code for first and second component.

<template> <div class="modal-body"> <div> <div class="row"> <div class="card col-md-4 square mr-2 mx-auto"> <label class="my-auto text-white text-center">1 hour</label> </div> <div class="card col-md-4 square ml-2 mx-auto"> <label class="my-auto text-white text-center">2 hours</label> </div> </div> <div class="row"> <div class="card col-md-4 square mr-2 mt-2 mx-auto"> <label class="my-auto text-white text-center">3 hours</label> </div> <div class="card col-md-4 square ml-2 mt-2 mx-auto"> <label class="my-auto text-white text-center">Unlimited</label> </div> </div> </div> <button class="btn btn-default float-right mt-2" v-on:click="selectPerson">Next</button> </div> </div> </template> <script> export default{ props:['selectedOption'], methods:{ selectPerson(){ this.$router.push({name:'SelectPersons'}); } } } </script>

second component

<template> <div class="modal-body"> <div class="text-center">Start booking your ticket now!</div> <div class="text-center"> <label>Step 2</label> </div> <div class="text-center"> <label>For how many persons?</label> </div> <div> <input type="number" class="form-control" name="numberOfPersons" placeholder="Enter number of persons here"> </div> <div> <button class="btn btn-default float-right mt-2" v-on:click="selectTimeSlots">Next</button> </div> </div> </template> <script> export default{ methods:{ selectTimeSlots(){ this.$router.push({name:'SelectTimeSlot'}); } } } </script>

Can anybody help me do it?

Categories: Software

custom modals with vue js scrolling issue

Mon, 2017-09-11 10:56

I'm creating bootstrap modals with vue js and i following tutorial but with a few tweaks, and it works just fine but now when i have long modals i got some issue about scrolling page, since it is only scrolling page behind the modals but not the modals

here is my modal.vue component

<template> <div class="modal-mask" @click="close" v-show="created"> <transition name="modal" enter-active-class="animated bounceInUp" leave-active-class="animated bounceOutDown" mode="out-in" v-on:enter="beforeEnter" v-on:after-leave="afterLeave" > <div class="modal-dialog" :class="size" v-if="show" @click.stop> <div class="modal-content"> <div class="modal-header" :class="color"> <button type="button" class="close" @click="close">&times;</button> <h6 class="modal-title"> <slot name="title"></slot> </h6> </div> <div class="modal-body"> <slot></slot> </div> <div class="modal-footer"> <slot name="button"></slot> </div> </div> </div> </transition> </div> </template> <script> export default{ props: ['show','color','size'], data(){ return{ created: false, } }, mounted(){ document.addEventListener("keydown", (e) => { if (this.show && e.keyCode == 27) { this.close(); } }); }, methods: { close(){ this.$emit('close'); }, beforeEnter(){ this.created = true }, afterLeave(){ this.created = false } } } </script> <style> .modal-mask { position: fixed; z-index: 9998; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, .5); transition: opacity .3s ease; } </style>

and to i just need to import this modal.vue component into any page that i needed.

so how to fix this scrolling issue?

Categories: Software

Add Mocha tests to Quasar and Vue.js

Mon, 2017-09-11 10:30

I recently moved from Vue.js to Quasar (which is just a set of components for Vue.js applications)

I have two different applications, one written using vue-cli and one with quasar-cli. The one with vue-cli has all test structure in place, I can just execute npm run unit and it finds all my mocha tests and run them.

I have then copied the same structure into my quasar project. It builds and run in dev mode correctly but when I execute this command:

cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run

I get these errors:

  • Typescript emitted no output for ..\src\sfc.d.ts
  • Module parse failed: ..\src\index.html Unexpected token (1:0) You may need an appropriate loader to handle this file type.
  • Module not found: Error: Can't resolve 'quasar/dist/quasar.start.css' in '..\src'

Somehow I am missing some configuration which is needed before I start karma. Any clue? In Vue.js using Typescript the same configuration is working just fine.

Categories: Software

Vue.js (2) actions coverage incomplete after unit test

Mon, 2017-09-11 09:32

after running correctly this unit test, the coverage is incomplete as I can see in lcov-report/src/vuex/actions.js.html .., only

return api.addNewShoppingList(shoppinglist)

is executed (1x), not the code inside the .then() block

thanks to anyone who can give me some feedback on this issue? ( if it's an issue.. or normal behavior )

actions.spec.js

import actions from '@/vuex/actions' import * as types from '@/vuex/mutation_types' describe('actions.js', () => { var server, store, lists, successPost successPost = {'post': true} beforeEach(() => { // mock shopping lists lists = [{ id: '1', title: 'Groceries' }, { id: '2', title: 'Clothes' }] // mock store commit and dispatch methods store = { commit: (method, data) => {}, dispatch: () => { return Promise.resolve() // static method }, state: { shoppinglists: lists } } sinon.stub(store, 'commit') // mock server server = sinon.fakeServer.create() server.respondWith('POST', /shoppinglists/, xhr => { xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(successPost)) }) server.autoRespond = true }) afterEach(() => { store.commit.restore() server.restore() }) describe('createShoppingList', () => { it('should return successful POST response', () => { let newList = { title: 'new list', id: '3' } actions.createShoppingList(store, newList).then((resp) => { expect(resp.body).to.eql(successPost) }) }) }) })

actions.js

import * as types from './mutation_types' import api from '../api' import getters from './getters' export default { populateShoppingLists: ({ commit }) => { return api.fetchShoppingLists().then(response => { commit(types.POPULATE_SHOPPING_LISTS, response.data) }) }, createShoppingList: (store, shoppinglist) => { return api.addNewShoppingList(shoppinglist) .then(() => { store.commit(types.ADD_SHOPPING_LIST, shoppinglist) store.dispatch('populateShoppingLists') }) }, }

api/index.js

import Vue from 'vue' import VueResource from 'vue-resource' Vue.use(VueResource) const ShoppingListsResource = Vue.resource('http://localhost:3000/' + 'shoppinglists{/id}') export default { addNewShoppingList: (data) => { return ShoppingListsResource.save(data) } }

mutations.js

import * as types from './mutation_types' import getters from './getters' import _ from 'underscore' export default { [types.POPULATE_SHOPPING_LISTS] (state, lists) { state.shoppinglists = lists }, [types.ADD_SHOPPING_LIST] (state, newList) { if (_.isObject(newList)) { state.shoppinglists.push(newList) } } }

mutations.types

export const POPULATE_SHOPPING_LISTS = 'POPULATE_SHOPPING_LISTS' export const ADD_SHOPPING_LIST = 'ADD_SHOPPING_LIST'

getters.js

import _ from 'underscore' export default { getLists: state => state.shoppinglists, }

console

mymac:lcov-report yves$ npm run unit > shopping-list@1.0.0 unit /Users/yves/Developments/shopping-list > cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/ [launcher]: Launching browser PhantomJS with unlimited concurrency launcher]: Starting browser PhantomJS [PhantomJS 2.1.1 (Mac OS X 0.0.0)]: Connected on socket -XTe5WWPBnSfAtg_AAAA with id 73492961 actions.js ... createShoppingList ✓ should return successful POST response PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 13 of 13 SUCCESS (0.086 secs / 0.034 secs) TOTAL: 13 SUCCESS =============================== Coverage summary ================== Statements : 64.44% ( 29/45 ) Branches : 50% ( 2/4 ) Functions : 81.25% ( 13/16 ) Lines : 64.44% ( 29/45 ) ================================================================

lcov-report/src/vuex/actions.js.html

import * as types from './mutation_types' import api from '../api' import getters from './getters' export default { createShoppingList: (store, shoppinglist) => { **1× return api.addNewShoppingList(shoppinglist)** .then(() => { store.commit(types.ADD_SHOPPING_LIST, shoppinglist) store.dispatch('populateShoppingLists') }) }, }
Categories: Software

element ui <el-select> Setting final value via asynchronous request

Mon, 2017-09-11 08:09

I want to do this: when I click the option,I send a request 。when the request success, I set the value with my clicked. when the request success fail,I keep the value origin ,before I clicked.

Categories: Software

vuejs2 dynamic css with dynamic html

Mon, 2017-09-11 07:04

A plugin I use creates dynamic html and I want to add a dynamic background-color using a hex passed via props.

This is the html in my component

<template> <div class="pagination" slot="pagination"></div> </template>

Generates dynamic HTML of this

<div class="pagination" slot="pagination"> <span class="swiper-pagination-bullet"></span> <span class="swiper-pagination-bullet"></span> </div>

The components receives props

props: ['primaryBgColor']

I can obviously see the color in the template if I write

<template> <div> {{ this.primaryBgColor }} </div> </template>

However when I write a style within the component like

<style> .swiper-pagination-bullet { background-color: {{ this.primaryBgColor }} } </style>

Webpack returns an error saying I have a CSS syntax error. Any ideas?

Categories: Software

Load more data using vue js when page is bottom area

Mon, 2017-09-11 06:40

I tried to make my Load More data when my page scroll to the bottom. The first thing is I make a div element that I put at the end of the data loop.

<div class="products"> <p>{{ status }}</p> <div class="product" v-for="(item, index) in items"> <div> <div class="product-image"><img :src="item.link" alt=""></div> </div> <div> <h4 class="product-title">{{ item.title }}</h4> <p>Price : {{ price }}</p> <button class="add-to-cart btn" @click="addItem(index)">Add Item To Cart</button> </div> </div> <div id="product-list-bottom"></div> </div>

Div element with id product-list-bottom I will detect it using scrollMonitor.js

My default data :

data: { status: 'Empty product', total: 0, items: [], cart: [], newSearch: 'anime', lastSearch: '', price: STATIC_PRICE, result: [] }

Inside mounted I detected scroll to bottom :

mounted: function() { this.onSubmit() var vueInstance = this var elem = document.getElementById('product-list-bottom') var watcher = scrollMonitor.create(elem) watcher.enterViewport(function() { vueInstance.appendItems() }) }

Inside mounted I call onSubmit :

onSubmit: function() { this.items = '' this.status = "Searching keyword '" + this.newSearch + "' on server ..." this.$http.get('/search/'.concat(this.newSearch)) .then(function(response) { this.lastSearch = this.newSearch, this.status = 'Find ' + response.data.length + ' data' this.result = response.data this.appendItems() }) }

And inside onSubmit I call appendItems function :

appendItems: function() { if(this.items.length < this.result.length) { var start = this.items.length var end = parseInt(this.items.length + 5) var append = this.result.slice(start, end) this.items = this.items.concat(append) console.log(append) } }

All goes well, but when I scroll down I get an error message : error display

This is because this line :

this.items = this.items.concat(append)

How do I make the data on xxx change (always added five new data from the array) according to the command on the line :

var end = parseInt(this.items.length + 5)

Thanks

Categories: Software

Passing data from table row into bootstrap modals

Mon, 2017-09-11 06:40

I'm creating vue js spa and what i trying to create is when i click on table row, it will show a modals with/showing data from the row that i clicked on.

here i have created my table

<tr class="cursor-pointer" @click="modalContextMenu"> <td> <img :src="'/images/artikel/' + props.item.images + 'n.jpg'" class="img-rounded img-sm" v-if="props.item.images"> <img :src="'/images/image-articlen.jpg'" class="img-rounded img-sm" v-else> </td> <td>{{props.item.name}}</td> <td>{{props.item.category.name}}</td> <td>{{props.item.writter}}</td> <td v-html="$options.filters.checkStatus(props.item.publish)"></td> <td v-html="$options.filters.checkStatus(props.item.featured)"></td> <td>{{props.item.created_at | publishDate}}</td> </tr>

at <tr> i put @click methods that make modal show and data that i want to show into modals is data from each <td> for that row / <tr>

right now my modalContextMenu methods is basically make modals visible/appear like this

modalContextMenu(){ this.modalShow= true; }
Categories: Software

[Rails][Vue] Empty array returned when fetching the children nested within a parent component. Any idea why is this happening?

Mon, 2017-09-11 02:04

I'm using Rails 5.1 + Webpack running Vue 2. I'm fairly new to Vue, not so new to Rails.

I'm building a navbar component starting from the Bulma navbar. My objective is to be able to dynamically create links in the navbar by simply adding a navlink element nested within.

In my application.html.erb I have already created this structure (navlink nested inside navbar).

In hello_vue.js I'm initializing the Vue components and assigning them to a root element (one for the navbar and one for the rest of the content).

In navbar.vue, I'd like to iterate through all the and create a menu item accordingly. In order to do so, I added an empty navlinks data to navbar that I want to populate once it gets mounted() by fetching all its children (the nested navlink tags).

This is however not working, whenever I reference this.$children I get an empty array. Any idea why is this happening?

This is all the code.

application.html.erb

<!DOCTYPE html> <html> <head> <title>RailsVue</title> <%= csrf_meta_tags %> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> <%= stylesheet_pack_tag 'hello_vue' %> </head> <body> <div id="navbar-container"> <navbar> <navlink href="http://google.com"> Link 1 </navlink> <navlink href="http://facebook.com"> Link 2 </navlink> </navbar> </div> <%= yield %> <%= javascript_pack_tag 'hello_vue' %> </body> </html>

hello_vue.js

import Vue from 'vue/dist/vue.esm' import App from './app.vue' import Navlink from './components/navlink.vue' import Navbar from './components/navbar.vue' const navbar = new Vue({ el: "#navbar-container", components: { Navbar, Navlink } }) const app = new Vue({ el: '#hello', data: { message: "Can you say hello?" }, components: { App } })

navbar.vue

<template> <div> <nav class="navbar is-transparent"> <div class="navbar-brand"> <a class="navbar-item" href="http://bulma.io"> <img src="http://bulma.io/images/bulma-logo.png" alt="Bulma: a modern CSS framework based on Flexbox" width="112" height="28"> </a> <div class="navbar-burger burger" data-target="navMenuTransparentExample"> <span></span> <span></span> <span></span> </div> </div> <div id="navMenuTransparentExample" class="navbar-menu"> <div class="navbar-start"> <a v-for="navlink in navlinks" class="navbar-item" :href="navlink.href"> <slot></slot> </a> </div> </div> </nav> </div> </template> <script> import Navlink from './navlink.vue' export default { name: "Navbar", data: function () { return { navlinks: [] } }, created: function(){ // let children = this.$children; console.log(this.$children); // this.navlinks = this.$children; // this.navlinks = this.$children; } } </script>

navlink.vue

<template> <div class="navlink"> <slot></slot> </div> </template> <script> export default { name: "Navlink" } </script>
Categories: Software

vuejs not working on the vps

Sun, 2017-09-10 23:52

the initialized app ( vue init webpack my-project ) compiles successufly on the vps but when visiting "servername:8080" it renders nothing, the terminal log: DONE Compiled successfully in 3245ms

Listening at http://localhost:8080

(node:23617) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Exited with code 3 (node:23617) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

the browser console shows this error: Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH app.js

thanks in progress :)

Categories: Software

VueJS random number gets generated only once

Sun, 2017-09-10 23:39

I want to make a simple VueJS app with the ability to use multiple APIs, grab an image and display it to the user. This is my first try with Vue after watching some videos of a course, so please don't hate me if I dont use a VueJS function but use pure JS.

I want that the user clicks a button, then it will request an image from an API. What works is that it picks an api randomly, but for the Flickr API I need to specify a tag (which are saved in an array, picked randomly too). But it only picks the tag once and every time I call the function again it's the same tag! Means the function only gets executed once the page is reloaded.

Why is it like this and how can I fix it? Thanks in advance.

My code so far

var vm = new Vue({ el: '#app', data() { return { // some data apis: [this.flickr(), this.desktopper()], wallpaper: '', wallpapers: [], screenWidth: window.screen.width, screenHeight: window.screen.height, } }, methods: { // The random function randomNumber(min, max) { return Math.floor(Math.random() * (max - min) + min); }, // The main function, calls an api and should get the image source requestWallpaper() { var wallpaper = this.apis[ this.randomNumber(0, this.apis.length) ]; console.log(wallpaper); }, // Flickr API request random image flickr() { // Most popular tags of all time on Flickr (tags are needed to request images)... var popularTags = ['sunset','beach','water','sky','red','flower','nature','blue','night','white','tree','green','flowers','portrait','art','light','snow','dog','sun','clouds','cat','park','winter','landscape','street','summer','sea','city','trees','yellow','lake','christmas','people','bridge','family','bird','river','pink','house','car','food','bw','old','macro','music','new','moon','orange','garden','blackandwhite']; // Grab a random tag var tag = popularTags[ this.randomNumber(0, popularTags.length) ]; return tag; }, // Desktopper.co API request random image desktopper() { return 'desktoppr'; } } });
Categories: Software

Testing Vuex action that calls external api

Sun, 2017-09-10 22:19

In my Vue.js project I have the following Vuex action:

import { HTTP } from '@/services/http' export const actions = { loginUser ({ commit }, params) { HTTP.post( 'v1/login', { email: params.email, password: params.password } ).then(response => { localStorage.setItem('access_token', response.data.token) commit('SET_USER', response.data) }).catch(error => { commit('SET_LOGIN_ERROR', error.response.data.error) }) } }

I'm using Mocha + Karma for unit tests. How can I test that action?

Categories: Software

Firebase does multiple calls even with if/else statement JS

Sun, 2017-09-10 22:04

I am building an app with Vue and also Firebase. I am new to Firebase and i've some problems with it. I try to store names + emails in the database. What I want is to check first if the email is already in the database and if not, run another function that will store the name + email. If the email is stored in the database I would like to output an alert and cancel the submit.

So the check of the email in the database is going quite well, it will output an alert, and also I am able to retrieve the data. But where the problem lays is that when I enter an email that is not in the database. When I enter a new email (and name) it will check the database and return false but then right away does another call (I dont know why, that's the problem I guess) and it will return true, and the alert of already being there, at the same time. Then it will proceed to another function to store the data because that was the output of the first call (which was false).

My JS code:

checkForm() { let app = this; if (this.name == '' || this.emailadress == '') { alert('You have to fill out the form'); } else { app.getFirebase(); } }, getFirebase() { let app = this; var ref = firebase.database().ref().child('/aanmeldingen/'); ref.on('value', function(snapshot) { const array = []; snapshot.forEach(function(childSnapshot) { var checkEmail = childSnapshot.val().email; array.push(checkEmail); }); const res = array.includes(app.emailadress); console.log(array); console.log(res); if(res) { alert('You already have entered the giveaway'); } else if (res == false) { app.store(); } }); }, store() { this.step_two = false; this.active_two = false; this.active_three = true; this.step_three = true; let app = this; firebase.database().ref('/aanmeldingen/').push({ username: app.name, email: app.emailadress, }); }

Screenshot of console (entered Jane, not in the database)

enter image description here

Categories: Software

Pages