Software

Upload file from VueJS app to API in Laravel

Vuejs - Wed, 2017-09-13 10:13

I'm trying to upload a file (Excel sheet) from a front-end app build with VueJS to an API build with Laravel 5.5. I've some form request validation which says to me that The file field is required. So the file doesn't get uploaded to my API at all.

VueJS file upload:

onFileChange(e) { let files = e.target.files || e.dataTransfer.files; if (files.length <= 0) { return; } this.upload(files[0]); }, upload(file) { this.form.file = file; this.form.put('courses/import') .then((response) => { alert('Your upload has been started. This can take some time.'); }) .catch((response) => { alert('Something went wrong with your upload.'); }); }

this.form is a Form class copied from this project but the data() method returns a FormData object instead of a object.

The route:

enter image description here

FormRequest rules:

public function rules() { return [ 'file' => 'required', ]; }

If I look to the Network tab in Chrome DevTools it does seem that the request is send correctly: (image after click).

I've tried a lot of things, like sending the excel as base64 to the api. But then I couldn't decode it correctly. So now I'm trying this, but I can't solve the problem. Any help is much appreciated.

Categories: Software

Unable to display data from Firebase Database using Vue.js

Vuejs - Wed, 2017-09-13 09:52

I have connected my Vue app to my Firebase Database and am able to see the resulting JSON in my Vue Dev Tools when I inspect the page on my localhost, for example:

users:Array[10] 0:Object .key:"99" City:"Richmond" Date of Birth:"9/16" Email:"fakeemail@gmail.com" Gender:"F" Home Phone:"" Ministry:"Campus" Name:"Doe, Jane" State:"VA" 1:Object 2:Object 3:Object etc.

In my App.vue file, I have the following code to output the data:

... <tbody> <tr v-for="user in users"> <td>{{ user.name }}</td> <td>{{ user.city }}</td> <td>{{ user.state }}</td> </tr> </tbody> ...

This outputs a table with the correct number of rows (10), but each table cell is blank. None of the data is printed. I'm guessing my references to the table using user.name, user.city, and user.state are not correct? Can you see if I'm doing something wrong? Thanks!

P.S. I have set the Rules to allow anyone to read/write to this database so I don't think permissions are the issue.

Categories: Software

Vues.js unit test w Karma-Mocha-HeadlessChrome , why message INFO about Vue Devtools?

Vuejs - Wed, 2017-09-13 09:48

running my unit tests, I am always getting this info messsage even if I already added the Devtools extension in my Chrome browser ?

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 ChromeHeadless with unlimited concurrency [launcher]: Starting browser ChromeHeadless HeadlessChrome 0.0.0 (Mac OS X 10.12.6)]: Connected on socket s3ED3TVFNjuvVojoAAAA with id 22013100 INFO LOG: 'Download the Vue Devtools extension for a better development experience: https://github.com/vuejs/vue-devtools'

any way to get rid of it ?

Categories: Software

Vue how to ensure async requests from both components have succeeded?

Vuejs - Wed, 2017-09-13 09:36

I have 2 components that each perform an AJAX requests with axios:

axios.get(this.ajaxUrl) .then((response) => {

Both of these components are hooked up to a Vuex store and I need to perform an action that ensure both async requests have succeeded.

To do this I need to have something in place which waits for both successful AJAX requests and only fires at that point.

I is not hard to do this for a single AJAX requests, I could set a property in my store like ajaxSuccess which defaults to false. When that property is being set to true I could simply use a watcher to respond to it and perform my event.

I have used this construct before and it works fine. How would I do this for multiple AJAX requests though?

Categories: Software

How to display space instead undefined and null in vue.js template?

Vuejs - Wed, 2017-09-13 09:32

This is Vue.js template

<strong>{{userdata.phone}}</strong>

When userdata.phone == null or userdata.phone == undefined, I would like to show space. for example

<strong> {{ userdata.phone | !null | !undefined }} </strong>

Is it possible?

Categories: Software

Errors with Vue values containing underscores

Vuejs - Wed, 2017-09-13 09:27

I'm having problems with Vue values that contains underscores, like this:

{{ employee.acf.user_phone }}

I'm getting console errors telling me:

[Vue warn]: Error in render function: "TypeError: Cannot read property 'user_phone' of undefined"

TypeError: Cannot read property 'user_phone' of undefined

However, the data is displayed in the template (it takes a while though), and Vue debugger in Chrome also shows the data correctly. This problem only seems to arise with the values that contains underscores between words. I know I shouldn't start values with underscores, but underscores between words in values should not be problematic right? What could be the problem here?

My data looks like this:

{ "employee":{ "id":1, "name":"name", "url":"", "description":"Lorem ipsum", "link":"http://localhost:8000/employee/john/", "slug":"john", "avatar_urls":{ "24":"http://0.gravatar.com/avatar/7sdb137ab174c6460503dee38a0a86cea?s=24&d=mm&r=g", "48":"http://0.gravatar.com/avatar/7sdb137ab174c6460503dee38a0a86cea?s=48&d=mm&r=g", "96":"http://0.gravatar.com/avatar/7sdb137ab174c6460503dee38a0a86cea?s=96&d=mm&r=g" }, "user_email":"useremail@gmail.com", "acf":{ "user_department":{ "term_id":3, "name":"marketing", "slug":"marketing", "term_group":0, "term_taxonomy_id":3, "taxonomy":"department", "description":"", "parent":0, "count":1, "filter":"raw" }, "user_office":"New York", "user_title":"My fancy title", } } }

Javascript/Vue looks like this:

(function($) { var employeeProfileElement = document.getElementById('vue-employee-profile'); var rest_url = WPsettings.rest_url; var nonce = WPsettings.nonce; if ( employeeProfileElement ) { var EmployeeProfile = new Vue({ el : employeeProfileElement, data() { return { employee: {}, errors: [], loading: true } }, created: function(){ employee = axios.get(rest_url + 'users/' + '1') // add authentication with nonce .then(response => { this.employee = response.data; this.loading = false; }) .catch(e => { this.errors.push(e); console.log(this.errors); }); } }); } })(jQuery);
Categories: Software

V-model multiple field with keys

Vuejs - Wed, 2017-09-13 09:08

Hi I would like to ask if how can I construct my data for multiple field with keys. Currently I'm getting undefined quantity and bidrate.

<td> <div class="field"> <div class="control"> <input v-numeric value="" class="input" type="number" placeholder="0" @keypress="validateQuantity" v-model="selectedContainers[index].quantity" > </div> </div> </td> <td> <div class="field"> <div class="control"> <input v-numeric.decimal class="input" type="number" placeholder="0" @keyup="validateBidRate" v-model="selectedContainers[index].bidrate" > </div> </div> </td>

Here's the screenshot of my UI:

enter image description here

Categories: Software

How to display images that have been fixed orientation image?

Vuejs - Wed, 2017-09-13 07:03

I use collaborate https://github.com/blueimp/JavaScript-Load-Image and https://github.com/blueimp/JavaScript-Canvas-to-Blob to fix orientation

My code in vue component like this :

<template> <div> ... </div> </template> <script> export default { ... data() { return { items: [1,2,3,4,5], clicked: [], selectedImage: null, image: [] } }, methods: { changeImage(item, $event) { const self = this this.selectedImage = $event.target.files[0] loadImage( $event.target.files[0], function (img) { img.toBlob( function (blob) { // create a form const form = new FormData(); form.append('file', blob, $event.target.files[0].name); // define the done handler const onDone = (response) => { if (!$.trim(response)) { alert('No response'); } else { const files = $event.target.files || $event.dataTransfer.files if (!files.length) return; self.createImage(item, response) } } // define th post options const options = { url: window.Laravel.baseUrl+'/product/addImageTemp', type: "POST", data: form, enctype: 'multipart/form-data', processData: false, // tell jQuery not to process the data contentType: false // tell jQuery not to set contentType } // submit the image $.ajax(options).done(onDone); }, $event.target.files[0].type ); }, { maxWidth: 600, canvas: true, pixelRatio: window.devicePixelRatio, downsamplingRatio: 0.5, orientation: true } // Options ); }, createImage(item, response) { const image = new Image() const reader = new FileReader() reader.onload = (e) => { this.image[item] = e.target.result this.$set(this.clicked, item, true) }; reader.readAsDataURL(this.selectedImage) } } } </script>

The code is works

If I upload image, it will fix orientation and save in folder. And also display in browser

My problem is the image displayed in the browser is an image that has not fixed orientation. I want the image shown is a image that had fix orientation image.

Information

I have 5 picture boxes if user uploads the image in box 3, it will show in box 3

Categories: Software

Why fail to call method in vue component if collaborate with a plugin?

Vuejs - Wed, 2017-09-13 05:11

I get reference to fix orientation image from here :

https://github.com/blueimp/JavaScript-Canvas-to-Blob

I try in vue component like this :

<template> <div> ... </div> </template> <script> export default { ... methods: { ... changeImage(item, $event) { ... loadImage( $event.target.files[0], function (img) { img.toBlob( function (blob) { // create a form const form = new FormData(); form.append('file', blob, $event.target.files[0].name); // define the done handler const onDone = (response) => { if (!$.trim(response)) { alert('No response'); } else { const files = $event.target.files || $event.dataTransfer.files if (!files.length) return; this.createImage(item, response) ... } } // define th post options const options = { url: window.Laravel.baseUrl+'/product/addImageTemp', type: "POST", data: form, enctype: 'multipart/form-data', processData: false, // tell jQuery not to process the data contentType: false // tell jQuery not to set contentType } // submit the image $.ajax(options).done(onDone); }, $event.target.files[0].type ); }, { maxWidth: 600, canvas: true, pixelRatio: window.devicePixelRatio, downsamplingRatio: 0.5, orientation: true } // Options ); }, createImage(item, response) { ... } } } </script>

It works. It success upload image in folder. But on the console exist error :

Uncaught TypeError: Cannot read property 'createImage' of undefined

The error here : this.createImage(item, response)

Seems the error because it cannot use this in function (img) {

How can I solve this problem?

I need this plugin to fix orientation image

Categories: Software

Unexpected keyword 'import' in WebPack Django and Vue.js project

Vuejs - Wed, 2017-09-13 01:59

I have a simple project where I am using Django, Webpack and Vue.js. When I build a static bundle upon load it seems like my bundle is not compiled correctly. I get an error in JavaScript console:

[Error] SyntaxError: Unexpected keyword 'import' (anonymous function) (main-dd2bbbf09bf9a252a3c7.js:47)

I tried to keep my webpack.config.js really simple:

var path = require("path"); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { context: __dirname, entry: './frontend/js/main', output: { path: path.resolve('./frontend/bundles/'), filename: "[name]-[hash].js", }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), ], resolve: { extensions: ['', '.js', '.vue', '.json'], }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { } // other vue-loader options go here } }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } } ], }, }

.babelrc looks like this:

{ "presets": [ ["env", { "modules": false }] ] }

main.js (which ultimately blows up) is simple:

import Vue from 'vue' import App from './App.vue' new Vue({ el: '#app', render: h => h(App) })
Categories: Software

Using Framework7+Vue's smart-select with a v-model

Vuejs - Wed, 2017-09-13 01:37

I've tried unsuccessfully to get a v-model to work correctly with the smart-select form, and looking through the component source I can't find where the smart-select value is being saved at all. The framework7-vue docs are frustratingly lacking in terms of showing how to use the framework7 items in an actually useful way.

<f7-list form> <f7-list-item smart-select smart-select-searchbar title="Ladders" smart-select-open-in="popup" v-model="selectedLadders" v-on:change="console.log('onChange')" v-on:input="console.log('onInput')"> <select name="ladders" multiple="multiple" > <option v-for="ladder in LadderConfigs" :key="ladder.key" :value="ladder.key" :input-value="ladder.key">{{ladder.name}}</option> </select> </f7-list-item> </f7-list> ... watch: { selectedLadders(new) { console.log("ladders changed:", new) }, }

Am I missing some hidden field, messed up my implementation, or something else? I already had to find the un-documented input-value prop for the radio select to work, so I wouldn't be surprised if I'm missing something here too.

Thanks!

Categories: Software

How to set Vue.http.post data using Vue to send data to Laravel route?

Vuejs - Wed, 2017-09-13 01:16

I want to send a post request to Laravel backend using Vue.js. I'd like to make it without any extra library. I am making a pure Vue.http.get request and it works like a charm. For testing Laravel route and Controller returned data, I've made a ajax request in my template, which also works fine, returning the correct data. However, when I use Vue, via Vue.http.post('My/Controller/Route',data) it doesn't sends the post data to the Controller.

My Vue.js method:

export default { data() { return { dados: {view: 'dia', pro: [], data: 'Setembro 11, 2017'} } }, method:{ this.dados.pro = this.checkedNames; // returned by another Vue piece of code - console.log() returns the correct data for this var return Vue.http.post('/admin/getAgendamentosPorProfissional', this.dados).then( (response) => { console.log(response.body); }, (response) => { console.log("Error"); console.log(response); console.log(response.body); }); } }

My Laravel Controller function:

public function getAgendamentosPorProfissional(){ // $view = $_POST['view']; // $pro = $_POST['pro']; // $data = $_POST['data']; $post = $_POST; return response()->json(array('post' => $post),200); }

It returns:
{post: Array(0)}

My jQuery AJAX function:

$.ajax({ type:'POST', url:'/admin/getAgendamentosPorProfissional', data: {"data": data, "view": view, "pro": [pro],"_token": "{{ csrf_token() }}"}, success:function(data){ console.log("AJAX - /admin/getAgendamentosPorProfissional"); console.log(data); } });

It returns:

post: data: "Setembro 11, 2017", pro:["75"] view"dia" _token:"6LviacS2KoBqjXxTsFhnTtAQePuEzZ49OMwqBmbM"

It's not a CORS issue, since it returns the correct data from the requested url in laravel. How can I fix this?

Categories: Software

chartjs - multi axis line chart - cannot read property 'min' of undefined

Vuejs - Wed, 2017-09-13 00:12

When running the below code without the scales and yAxisID values, it renders a 2 line chart with both lines on the same axis

When adding these elements in order to get a split axis, it returns the js error cannot read property 'min' of undefined and the canvas is blank.

Not sure if his should make a difference, but data is a json object returned through an ajax request by way of a vue.js method.

var ctx = document.getElementById("chart_canvas").getContext('2d') var basic_line = new Chart(ctx, { type: 'line', data: { labels: data.labels, datasets: [{ label: 'Price', yAxisID: 'B', fill: false, borderColor: ["#668cff"], data: data.price }, { label: 'Sales', yAxisID: 'A', fill: false, borderColor: ["grey"], data: data.sales }], options: { scales: { yAxes: [{ id: 'A', position: 'left', }, { id: 'B', position: 'right' }] }, responsive: true, maintainAspectRatio: false } } })
Categories: Software

Vuejs Slot Parent Child

Vuejs - Tue, 2017-09-12 22:34

How do I get these 2 components to work together?

Vue.component('parent', { template: ''+ '<slot name="foo"></slot>'+ '' }); Vue.component('child', { template: ''+ '<div slot="foo">bar</div>'+ '' });

I thought I could do something like this but it didn't appear to work

Vue.component('parent', { components: [ 'child' ], template: ''+ '<slot name="foo"></slot>'+ '' });

Here is a JS Fiddle https://jsfiddle.net/3fjmLL52/

Categories: Software

Vuejs router beforeEach : if state is true, run code, else load async data into state, then run same code

Vuejs - Tue, 2017-09-12 21:42

I'm using VueJS, VueRouter and VueX in my SPA.
I want my app to load some data at start up, required under multiple routes. This data is stored in the VueX's state.
Here's what I've done with my router, with explanations in the comments, hoping it's clear enough :

router.beforeEach((to, from, next) => { if (!store.getters.getStartUp()) { // a getter function returning boolean value of a state flag property named startUp, false by default and set to true when I have loaded the required data (in the created method of the main Vue instance (see next code example) const watcher = store.watch(store.getters.getStartUp, () => { watcher(); // cancel the watcher // Here is the code block I need to reuse if (to.matched.some(record => record.meta.forVisitors)) { if (Vue.auth.isLoggedIn()) { next({ path: '/' }); } } else if (to.matched.some(record => record.meta.forAuth)) { if (!Vue.auth.isLoggedIn()) { next({ path: '/login' }); } } next(); // end of code block }); } else { // execute the same code block which is ran in the watcher. // what is the best pattern to do that ? // a simple function defined in the beforeEach ? using Promises ? } });

and here is what I put in the created method of the main Vue instance :

created() { if (!store.state.startUp) { Promise.all([ store.dispatch('getSomeData1'), store.dispatch('getSomeData2'), ]) .then(() => { store.commit('setStartUp'); // set the state flag property to true }); } }

thanks !

Categories: Software

Mock backend in nightwatch.js tests

Vuejs - Tue, 2017-09-12 20:38

In my Vue.js app I'm using nightwatch to test my app. I have the following spec:

module.exports = { 'wrong email or password': function (browser) { const devServer = browser.globals.devServerURL var nock = require('nock'); var couchdb = nock('http://localhost:3000/') .get('api/v1/login') .reply(401, { error: 'dupa' }); browser .url(devServer + '/login') .setValue('input[type=email]', 'email@example.com') .setValue('input[type=password]', 'password') .click('.login') .assert.containsText('#app', 'Niepoprawny email lub hasło.') .end() } }

In my test I'm trying to use https://github.com/node-nock/nock. But unfortunately this not mocks any requests. What I'm doing wrong?

Categories: Software

Vue.js filter a list

Vuejs - Tue, 2017-09-12 20:03

I am new to Vue.js. I'm trying to display a filtered list based on the value of another object. The select sets the value of the object called activeSet. That value is the key in the sets object. If that keys value is greater than 0 I want to display it in the list and sort by it. Here is my code:

JS

var vm = new Vue({ el: '#app', data: { activeSet: 'all', computed: { activeContents: songs.filter(function(song) { return (song[activeSet] > 0); }) }, songs: { a: { title: 'Hound Dog', all: 0, set1: 2 }, b: { title: 'Long Gone', all: 1, set1: 0 }, b: { title: 'Novermber Rain', all: 2, set1: 3 } }, sets: { all: { name: 'All Songs' }, set1: { name: 'Acoustic' } } } })

HTML

<div id="app"> <select v-model="activeSet"> <option v-for="(set,key) in sets" :value="key">{{set.name}}</option> </select> <ul id="menu"> <li v-for="(song,key) in activeContents" :id="key" :is-active="song.show" :key="key" @click="activeSong=key">{{ song.title }}</li> </ul> </div>

Fiddle Here is the fiddle

Sidenote: If the value is above 0 it needs to be included and then sorted by that value. I haven't even dived into sorting yet so bonus points if you can sort by the value of those that are greater than 0.

Categories: Software

Unable to load module with inject-loader

Vuejs - Tue, 2017-09-12 19:36

In my vue.js project I have the following file at src/api/user.js

import { HTTP } from '@/services/http' export const user = { login (email, password) { return HTTP.post('v1/login', { email: email, password: password }) } }

I'm trying to load this file using inject-loader inside my specs:

const actionsInjector = require('inject-loader!../../../../src/api/user')

it returns me following error:

Module not found: Error: Can't resolve '../../../../src/api/user' in '/home/mateusz/projects/e_lessons_frontend/test/unit/specs/store/user'

How can I fix that?

UPDATE:

After adding one extra ../ I have new error:

Error: Some of the injections you passed in are invalid. Valid injection targets for this module are: - @/services/http The following injections were passed in: - @/api/user The following injections are invalid: - @/api/user

This caused by this line of code in my tests:

// create the module with our mocks const actions = actionsInjector({ '@/api/user': { login (email, password) { return { token: 'dupa' } } } })

Any ideas?

Categories: Software

How to retrieve User name in Vue component with Laravel

Vuejs - Tue, 2017-09-12 19:12

I have a vue component that will send a message and I want to send the logged in user name. I'm using laravel 5.5

methods:{ sendMessage(){ this.$emit('messagesent', { message:this.messageText, user: { name : {{Auth()::user()->name}} //Here is where it should be } }); this.messageText = ''; } }

I already tried using

{{Auth()::user()->name}} Auth()::user()->name

Both give errors. How can I retrieve the name?

Categories: Software

VueJS (another) virtual scroll implementation

Vuejs - Tue, 2017-09-12 18:58

I'm trying to implement virtual scroll for items with variable heights. Every other implementation I've seen so far requires you to specify the height when declaring the module.

I have the list implemented as follows:

<div class="main" ref="main" @scroll="handleScroll" > <div :style="{ 'margin-top':padTop+'px', 'margin-bottom':padBottom()+'px' }"> <div v-for="i in maxDisplayed"> <slot :name="'s-' + (i + startIndex - 1)">{{i + startIndex - 1}}</slot> </div> </div> </div>

The handleScroll function (the one failing) is this:

handleScroll (e) { if (!this.$refs.main || this.$refs.main.scrollTop == undefined) return; //can't calculate if there's nothing displayed // top of the items list container relative to the page top let mainTop = this.$refs.main.getBoundingClientRect().top; // bottom position of the first "displayed" item let itemTop = this.$refs.main.children[0].children[0].children[0].getBoundingClientRect().top; let itemBottom = this.$refs.main.children[0].children[0].children[0].getBoundingClientRect().bottom; if (itemBottom < mainTop && (Object.keys(this.$slots).length > (this.startIndex + this.maxDisplayed))) { this.startIndex ++; this.heights.push(this.$refs.main.children[0].children[0].children[0].clientHeight); } else if (itemTop > mainTop && (this.startIndex > 0)) { this.heights.pop(); this.startIndex = Math.max(this.startIndex - 1, 0); } },

So far I have the code working perfectly when user is scrolling relatively slowly. But it fails when you scroll fast through the list. I suspect it has something to do with it not being able to catch all the children flying past the scroll window. Any help would be appreciated.

jsfiddle

Categories: Software

Pages