Software

Vuejs eventbus triggers multiple times due to webpack import outport?

Vuejs - 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

Vuejs - 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?

Vuejs - 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

Vuejs - 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

Vuejs - 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

Vuejs - 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

A Copyright Vote That Could Change the EU’s Internet

Mozilla Blog - Mon, 2017-09-11 09:01
On October 10, EU lawmakers will vote on a dangerous proposal to change copyright law. Mozilla is urging EU citizens to demand better reforms.

 

On October 10, the European Parliament Committee on Legal Affairs (JURI) will vote on a proposal to change EU copyright law.

The outcome could sabotage freedom and openness online. It could make filtering and blocking online content far more routine, affecting the hundreds of millions of EU citizens who use the internet everyday.

Dysfunctional copyright reform is threatening Europe’s internet

Why Copyright Reform Matters

The EU’s current copyright legal framework is woefully outdated. It’s a framework created when the postcard, and not the iPhone, was a reigning communication method.

But the EU’s proposal to reform this framework is in many ways a step backward. Titled “Directive on Copyright in the Digital Single Market,” this backward proposal is up for an initial vote on October 10 and a final vote in December.

“Many aspects of the proposal and some amendments put forward in the Parliament are dysfunctional and borderline absurd,” says Raegan MacDonald, Mozilla’s Senior EU Policy Manager. “The proposal would make filtering and blocking of online content the norm, effectively undermining innovation, competition and freedom of expression.”

Under the proposal:

  • If the most dangerous amendments pass, everything you put on the internet will be filtered, and even blocked. It doesn’t even need to be commercial — some proposals are so broad that even photos you upload for friends and family would be included.

 

  • Linking to and accessing information online is also at stake: extending copyright to cover news snippets will restrict our ability to learn from a diverse selection of sources. Sharing and accessing news online would become more difficult through the so-called “neighbouring right” for press publishers.

 

  • The proposal would remove crucial protections for intermediaries, and would force most online platforms to monitor all content you post — like Wikipedia, eBay, software repositories on Github, or DeviantArt submissions.

 

  • Only scientific research institutions would be allowed to mine text and datasets. This means countless other beneficiaries — including librarians, journalists, advocacy groups, and independent scientists — would not be able to make use of mining software to understand large data sets, putting Europe in a competitive disadvantage in the world.
Mozilla’s Role

In the weeks before the vote, Mozilla is urging EU citizens to phone their lawmakers and demand better reform. Our website and call tool — changecopyright.org — makes it simple to contact Members of European Parliament (MEPs).

This isn’t the first time Mozilla has demanded common-sense copyright reform for the internet age. Earlier this year, Mozilla and more than 100,000 EU citizens dropped tens of millions of digital flyers on European landmarks in protest. And in 2016, we collected more than 100,000 signatures calling for reform.

Well-balanced, flexible, and creativity-friendly copyright reform is essential to a healthy internet. Agree? Visit changecopyright.org and take a stand.

The post A Copyright Vote That Could Change the EU’s Internet appeared first on The Mozilla Blog.

Categories: Software

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

Vuejs - 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

Vuejs - 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

Vuejs - 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

Vuejs - 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?

Vuejs - 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

Vuejs - 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

Vuejs - 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

Vuejs - 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

Vuejs - 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

vue.js 2 how to properly nest components

Vuejs - Sun, 2017-09-10 21:58

Can you please tell me how to properly add components to other components? The example below does not work. The child component is not displayed inside the parent.

<div id="app"> <parent> <child></child> </parent> </div> <template id='child'> <div>child component</div> </template> <template id='parent'> <div>parent component</div> </template> <script> var child = { template: '#child', data: function () { return {} } }; var parent = { template: '#parent', data: function () { return {} } }; new Vue({ el: '#app', components: { 'parent': parent, 'child': child } }) </script>

sample: https://jsfiddle.net/05gc05sk/1/

how to properly nest components?

Categories: Software

vue-router in production (serving with Go)

Vuejs - Sun, 2017-09-10 21:44

I'd like to separate client and server completely, so I created a vuejs project with vue init webpack my-project. In this project I'm using vue-router for all my routing (this includes special paths, like /user/SOMEID..

This is my routes.js file:

import App from './App.vue' export const routes = [ { path: '/', component: App.components.home }, { path: '/user/:id', component: App.components.userid }, { path: '*', component: App.components.notFound } ]

When I run the application using npm run dev everything works perfectly. I'm now ready to deploy to cloud, so I ran npm run build. Since I need to use a HTTP Server, I decided to use Go for that as well.. this is my Go file:

package main import ( "fmt" "github.com/go-chi/chi" "github.com/me/myproject/server/handler" "net/http" "strings" ) func main() { r := chi.NewRouter() distDir := "/home/me/code/go/src/github.com/me/myproject/client/dist/static" FileServer(r, "/static", http.Dir(distDir)) r.Get("/", IndexGET) http.ListenAndServe(":8080", r) } func IndexGET(w http.ResponseWriter, r *http.Request) { handler.Render.HTML(w, http.StatusOK, "index", map[string]interface{}{}) } func FileServer(r chi.Router, path string, root http.FileSystem) { if strings.ContainsAny(path, "{}*") { panic("FileServer does not permit URL parameters.") } fs := http.StripPrefix(path, http.FileServer(root)) if path != "/" && path[len(path)-1] != '/' { r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP) path += "/" } path += "*" r.Get(path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fs.ServeHTTP(w, r) })) }

I'm able to load the home page (App.components.home) where everything seem to work (the css, the images, translations, calls to and responses from the server).. but when I try to open other routes that should either result in 404 or load a user, then I just get the response 404 page not found in plaintext (not the vue notFound component it's supposed to render)..

Any ideas what I'm doing wrong and how to fix it?

Categories: Software

How to call a vue component method from another js file

Vuejs - Sun, 2017-09-10 21:41

I have a Vue v2.3.4 (quasar-framework v0.14.2) modal ComponentA working when clicking on a button in the same component. The MyModal component seems to work fine (as I can trigger it with a button). However I have code in a separate util.js file which should trigger the modal (from a 'myUtilElement'). How can I do that?

ComponentA.vue

<template> <div> <div id='lotsofstuff'></div> <myModal ref="modalTest"></myModal> </div> </template> <script> import MyModal from '../MyModal.vue' export default { name: 'componentA', components: {MyModal}, methods: { openModal: function () { this.$refs.myModal.open() }, otherMethods:...etc. }

Util.js

import ComponentA from '../ComponentA.vue' myUtilElement.addEventListener('click', triggerModal, false) function triggerModal () { ComponentA.methods.openModal() }

I now get following error in the console:

Uncaught TypeError: Cannot read property 'openModal' of undefined at HTMLElement.triggerModal
Categories: Software

setTimeout in Vue method not working

Vuejs - Sun, 2017-09-10 21:38

In my small Vue application, I'm trying to call the same method (emptyDivision) with different parameters from within another method (buttonClick). I set a 5-second timeout for the second invocation of that method, but this delay is not being recognized when I trigger these two functions by executing buttonClick.

<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.1.1/vuex.min.js"></script> </head> <body> <div id="app"> <button v-on:click="buttonClick">Simulate Placement</button> <h1>Random Division 1</h1> <p>{{A.One}}</p> <p>{{A.Two}}</p> <h1>Random Division 2</h1> <p>{{B.One}}</P> <p>{{B.Two}}</p> </div> <script type="text/javascript"> new Vue({ 'el': '#app', 'data': { 'A': {'One': "", 'Two': "" }, 'B': {'One': "", 'Two': "" }, 'Division1': ["Steelers", "Ravens"], 'Division2': ["Broncos", "Raiders"], }, 'methods': { 'emptyDivision': function(division){ this.A[division] = this.popTeam(division)[0]; this.B[division] = this.popTeam(division)[0]; }, 'popTeam': function(division) { if (division === "One"){ return this.Division1.splice(Math.floor(Math.random()*this.Division1.length), 1); } return this.Division2.splice(Math.floor(Math.random()*this.Division2.length), 1); }, 'buttonClick': function() { setTimeout(function() {console.log("This appears after 3 seconds")}, 3000); setTimeout(this.emptyDivision("One"), 5000); /*Teams in division one ("Steelers" and "Ravens") should be propagated to the DOM after 5 seconds, but it's being evaluated at the same time as the invocation to this.emptyDivision("Two") */ this.emptyDivision("Two"); /* I expect ("Broncos" and "Raiders" to be rendered to the DOM first due to the timeout, but this is not happening*/ } } }) </script> </body> </html>

After inspecting the console, the three-second timeout log statement is evaluated and produces the expected behavior, but the five-second timeout to emptyDivision("one") does not appear to be working, as detailed by the comments I left in the above code.

Categories: Software

Pages