Software

How to save and retrieve file using pouchdb and vue js

Vuejs - Thu, 2017-08-03 19:16

Can someone help me on how to upload a file on pouchdb and display those uploaded files on page. I want to upload a file including name info of that file. When I check the fetch files using the console I can see [object object]. Am I doing the right thing? Any advice is well appreciated. Here is my code.

//Notes.vue // By the way Im using onsen ui for this <template> <v-ons-page> <v-ons-list> <v-ons-list-header>Auditing</v-ons-list-header> <v-ons-list-item v-for="note in notes"> <div class="left"> <img src="" alt=""> </div> <div class="center"> <span>{{ note._attachment['files'].data }} File here</span> </div> </v-ons-list-item> </v-ons-list> // Customize form for uploading file and info <v-ons-alert-dialog modifier="rowfooter" :visible.sync="dialogVisible" > <span slot="title">Create a Note</span> //File name of the file <v-ons-input float placeholder="Name of note" v-model="name" > </v-ons-input> // File <v-ons-input type="file" @change="onFileChange"></v-ons-input> <v-ons-button @click="addNotes(name)">Submit</v-ons-button> </v-ons-alert-dialog> </v-ons-page> </template>

//Here the methods for uploading and reading file uploaded

<script> import PouchDB from 'pouchdb' var db = new PouchDB('reviewerdb') export default { data() { return { dialogVisible: false, notes: [], file: '', name: '', path } }, mounted() { this.getNotes(); print('notes: ' + this.notes); },

//Methods just adding a desciption

methods: { onFileChange(event) { this.file = event.target.files[0]; }, addNotes() { db.put({ _id: 'notes', _attachments: { "file": { type: this.file.type, data: this.file } } }) }, getNotes() { db.get('notes', {attachments:true}).then(function (note) { this.notes = note; }); } } }

Categories: Software

Append as array inside array

Vuejs - Thu, 2017-08-03 19:10

I have an object that looks like this, and I can push data using below method. Also I initialize the types data.

myObj = { 1: ["a", "b", "c"], 2: ["c", "d", "e"], } data: { types: {} }, methods: { pushValue(key, value) { var obj = this.types if (obj.hasOwnProperty(key)) { var idx = $.inArray(value, obj[key]); if (idx == -1) { obj[key].push([value]); } } else { this.$set(obj, key, [value]); } }, }

It works fine.

However, now I want my object to look like this:

myObj = { 1: { "a": [ [],[] ], "b": [ [],[] ], } }

How can I modify my append function to append the elements like this?

Categories: Software

VueTable Passing Row Data to Callback method

Vuejs - Thu, 2017-08-03 18:52

I am looking to format a column with a URL. The URL is something like this project/id. Is there any way to achieve this? The column that needs to formatted doesn't have the primary ID of the project which needs to be passed as the URL parameter.

The callback method has to be something like

projecturl( value, data ) { return '<a href="/project/data.id">value</a>'; }

I mainly require a Column Modifier that has a hyperlink like this: http://prntscr.com/g3yev4 rather than just plain text like this: http://prntscr.com/g3yefn

Categories: Software

Connecting Vue to Express - 404 Not Found

Vuejs - Thu, 2017-08-03 17:50

I'm creating a simple app to practice connecting Vue to an Express server. I have a form that I'm attempting to send to the back end, but I can't seem to get my data to the back-end. The error I'm receiving is:

POST http://localhost:8080/login 404 (Not Found)

My best guess is that the method in my Vue can't find a matching route on my server? If so, I'm confused as I have a route for login.

In my Vue script:

const axios = require('axios'); export default { data: function() { return { user: { email: '', password: '' } } }, methods: { sub() { var user = { email: this.user.email, password: this.user.password } axios.post('/login', user) .then(res => console.log(res)) .catch(err => console.log(err)) } } }

On by back-end:

const path = require('path'); const express = require('express'); const app = express(); app.use(express.static(path.join(__dirname, '..'))); app.post('/login', function(req, res) { console.log("Server HIT!!!!!!!!!!!!!!!!!!!!") }) app.get('*', function (req, res) { return res.sendFile('../index.html'); }); app.listen(3000); console.log('Express server listening on port 3000');
Categories: Software

vue-google-maps not auto scaling

Vuejs - Thu, 2017-08-03 17:40

I seem to be having issues implementing Bounds with the https://github.com/xkjyeah/vue-google-maps package. Im trying to make sure all markers (even if there is only 1, centre is user latlong) are always inside the map viewport.

Excerpts below:

methods: { getMarkers() { let x = []; this.locations.forEach(function(item) { x.push({position: {lat:item.latitude, lng:item.longitude}, data: item}); }); this.markers = x; if(this.markers.length == 1) { this.locationData = this.markers[0].data; } } }, watch: { markers(markers) { const bounds = new google.maps.LatLngBounds() for (let m of markers) { bounds.extend(m.position) } this.$refs.gmap.$mapObject.fitBounds(bounds) } }, <gmap-map ref="gmap" class="map" :center="{lat:$store.state.latitude, lng:$store.state.longitude}" :zoom="zoom" :options="options" :scrollwheel="false" map-type-id="terrain" > <gmap-marker :key="index" v-for="(m, index) in markers" :position="m.position" :clickable="true" :draggable="false" @click="locationData = m.data" ></gmap-marker> </gmap-map>

If I console.log(bounds) I get

_.kd {f: id, b: bd} b:bd b:-2.4758634658720666 f:-2.443729561463897 __proto__:Object f:id b:53.117689120883 f:53.087672842818 __proto__:Object __proto__:Object

So it looks like Bounds is being set, but the map still has markers outside the viewport and it's not automatically resizing.

What am I doing wrong?

Categories: Software

How to get changes in the object properties inside the array with vue $watch?

Vuejs - Thu, 2017-08-03 16:07

I need to get object properties change inside the array. For to do that, I'm using vue.$watch. I read the documentation but I didn't get that.

The scenario is:

... data() { return { Questions: [{foo: 1}, {foo: 2}, {foo: 3}] } }, ... this.$watch("Questions", function (newVal, oldVal) { // something... }, { deep: true });

See the example on JsFiddle

Categories: Software

Vue unit testing - textContent doesn't contain expected propsData

Vuejs - Thu, 2017-08-03 15:59

Here is my component:

<template> <div> {{serviceConfig.name}} </div> </template> <script> export default { props: ['serviceConfig'] } </script>

In my test, I am setting serviceConfig like this:

it(`should render serviceConfig`, () => { const Constructor = Vue.extend(TestMe2); const comp = new Constructor({ propsData: { serviceConfig: '{ "name": "Apple" }' } }).$mount(); expect(comp.serviceConfig).to.equal('{ "name": "Apple" }'); // successfull expect(comp.$el.textContent).to.contain('Apple'); // unsuccessfull });

However, if I change my template so that I am rendering {{serviceConfig}} instead of serviceConfig.name, it works, but not what I want (since I just want the name, i.e. 'Apple').

Categories: Software

Selecting specific element in vue 2 inside v-for loop

Vuejs - Thu, 2017-08-03 15:49

Please see the code

<div v-for="msg in leftMsg"> div v-if="msg.last_sender" @click.prevent="loadMsg(msg)"> <tr :class="['active',{ 'seens' : !msg.seen, 'selected':msg.isActive}]"> // some html </tr> </div> </div> loadMsg(obj){ obj.isActive = !obj.isActive; }

The problem is, it is adding selected class properly but when I click another item it adds selected but doesn't remove the old one. How can I keep only the most recent clicked item selected?

Thank you.

Categories: Software

run loop backward in template in vuejs

Vuejs - Thu, 2017-08-03 15:40
<template> <li v-for="r in recent"> {{r}} </li> </template>

recent is an array .

I don't want to list contents of recent from 0 to n-1 .

Instead i want to list it from n-1 to 0.

I tried ->

<template> <li v-for="r=recent.length-1 ; r>=0 ; r--"> {{r}} </li> </template>

But, it didn't work.

Categories: Software

Vue.js, pass data to component on another route

Vuejs - Thu, 2017-08-03 14:49

Simple task to pass data from one page to another made a real headache to newbie in Vue.js Here is my router enter image description here

I'm rendering a form on "/" page, which make an API request, enter image description here

and I just want to pass data to another route page with another component enter image description here

Is it so hard to do in Vue? It made a real headache for me today. Get data from API, save & send to another component. How can I do it?

Categories: Software

Trouble with vue.js to get data from REST API

Vuejs - Thu, 2017-08-03 14:28

I'm trying to get data from a rest api using vue.js. But it's not working. It neither show response data nor showing error status. Can't figure it out what went wrong.

Here's my index.html

<html> <body> <script src="https://unpkg.com/vue"></script> <div id="app"> {{ message }} </div> <script> var url = "http://clients.itsd.com.bd/table-cartel/wp-json/wp/v2/categories"; var app = new Vue({ el: "#app", data: { message: "Hello!" }, methods: { work: function(){ alert(url); this.$http.get(url).then(function(response){ alert(response.data); this.message = response.data; }, function(error){ alert(error.statusText); }); } }, mounted: function(){ this.work(); } }); </script> </body> </html>

It's showing url, but not showing response.data or error.statusText.

Categories: Software

How to get data from server before component is mounted vue2.0

Vuejs - Thu, 2017-08-03 13:43

I've got a question like in the title
How to stop mounting the component in <router-view> until receive a data from server or how to get the data before the component is mounted to <router-view>

My files:

1st main.js

new Vue({ el: '#app', router, components: { Login, Start }, data: function(){ return{ info: null, } }, methods:{ bef: function(){ this.$http.get('xxx').then(function(response){ return response.body }); } }, beforeMount(){ this.info= this.bef() } })

2nd component file Comp.vue

export default{ name: 'start', data(){ return{ } }, beforeMount(){ console.log(this.$parent.info) } }

how to do it properly to get not null value, but response from the server?
Thank you in advance

Categories: Software

Node.js - admzip cannot compress images properly

Vuejs - Thu, 2017-08-03 13:33

Since a while I'm stuck at the import function of my quiz generator application, because adm-zip cannot compress images properly.

Here is the errors that are returned for each images being uncompressed from the zip archive.

And here is the code involved in the compression of the archive, that is the component's method exportExecute() :

var AdmZip = require('adm-zip') var zip = new AdmZip() var uid = this.uid if (this.$parent.env === 'development') { zip.addLocalFile(this.$root.dbLocation) zip.addLocalFolder('app/dist/illustration', 'app/dist/illustration') } else { zip.addLocalFile(this.$root.dbLocation, 'resources/app/dist') zip.addLocalFolder('resources/app/dist/illustration', 'resources/app/dist/illustration') } zip.addFile('.token', uid) zip.writeZip(location) /** confirmation dialog */ dialog.showMessageBox({ title: 'Confirmation', message: 'La base de donnée a bien été exportée.', buttons: ['Ok'] })

The importExecute() method is not required here since it's properly working and the problem is the archive itself.

Also, I tried another zip compression module, but only in production it returned a pipe error, I never understood why it did that.

I'm stuck on this since a while and this is the last thing to be done in order to finish and release my app. Whoever helps me with this will be inserted in a credit.

Many thanks in advance.

Categories: Software

Vue-Router is not getting my first dynamic segment on a route when using history API

Vuejs - Thu, 2017-08-03 13:04

I am making an online shop, which has two brands. Each of these brands contains 20+ products, which I want to display appropriately.

The urls work just fine when I enter a /single-product page from other pages, but if I hit refresh, essentially my first dynamic segment is discarded and replaced with the second one.

So if I enter this url in the adress bar (my website is in the folder /villebois):

http://localhost/villebois/wines/wine-brand1/my-awesome-single-wine

It's automatically replaced with this for some reason:

http://localhost/villebois/wines/my-awesome-single-wine

My routes looks like:

{ path: '/villebois/wines/:brand/:slug', component: SingleProduct, name: 'single-product' }, { path: '/villebois/wines/:brand', component: BrandContainer, name: 'single-brand' }

So the dynamic segment brand is overriden by slug. I am using Vue-router with the History API (note: if I use the default hash one, everything works perfectly)

Here is my .htaccess for configuring my server to serve index.php (I am using Wordpress) on every possible route:

<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /villebois/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /villebois/index.php [L] </IfModule>

TL:DR If I directly enter a page with route with two dynamic segments using the History API, for some reason the first segment always gets replaced with the second. If I enter it from another page or use hash history, it works just fine.

Categories: Software

VueFire object undefined

Vuejs - Thu, 2017-08-03 12:58

I have the following:

const firebase = { items: { source: db.ref('items'), asObject: true, readyCallback: function() { console.log('items retrieved!'); } } } new Vue({ el: '#app', firebase, render: (h) => h(App) });

If I look in the console of the browser, I get to see 'items retrieved!' after a few seconds, but when I write

{{ typeof items }}

in the template I get undefined. I followed the docs on the VueFire Github page but can't seem to get it working.

Anyone got any ideas?

Thx

Categories: Software

Vuex mutation only applied when committed manually in devtools

Vuejs - Thu, 2017-08-03 12:58

I have a mutation as follows:

[types.REMOVE_INVITATION] (state, removed_invitation) { state.invitations = _.filter(state.invitations, function (invitation) { return invitation.id !== removed_invitation.id; }); },

...which I run like so:

this.$store.commit(types.REMOVE_INVITATION, invitation);

This data is then displayed in a view like this:

<tr v-for="invitation in $store.state.group.invitations"> <td>@{{ invitation.email }} (pending)</td> <td class="has-text-right"> <button type="button" @click="revokeInvitation(invitation)" class="button is-warning">Revoke Invitation</button> </td> </tr>

This appears in the Vue devtools VueX tab as new line and the store data in the dev tools updates correctly. However the view does not update.

If I then click the "Commit This Mutation" link on this mutation in the devtools everything works as I expect it to - the view updates, and the invitation is removed from the list.

What is really confusing me is that I have another mutation that does essentially the same thing but which works fine:

this.$store.commit(types.REMOVE_GROUP_USER, user); [types.REMOVE_GROUP_USER] (state, removed_user) { state.group.users = _.filter(state.group.users, function (user) { return user.id !== removed_user.id; }); }, <tr v-for="(user, index) in $store.state.group.group.users" :key="user.id"> <td> @{{ user.username }} </td> <td class="has-text-right"> <button type="button" @click="kick(user)">Kick</button> </td> </tr>
Categories: Software

Register a component to an existing Vue.js instance

Vuejs - Thu, 2017-08-03 12:38

I'm new to Vue.js.

I want to register a local component as described over here:

https://vuejs.org/v2/guide/components.html#Local-Registration

The only issue is that I need to register a component to an existing Vue instance not while creating a new instance something like:

const app = new Vue({ el: '#app' }); app.component({ 'my-component': { template: '<div>A custom component!</div>' } });

I have tried Vue.extend for that, but not working.

Categories: Software

The method in Vue runs twice on click

Vuejs - Thu, 2017-08-03 12:25

Why does the method set runs twice? You can see the console when you click the star. If I remove @click="set(rating)" nothing happens so not like it is again called elsewhere.

http://jsfiddle.net/q22tqoLu/

HTML

<div id="star-app" v-cloak> <star-rating value="0"></star-rating> </div> <template id="template-star-rating"> <div class="star-rating"> <label class="star-rating__star" v-for="rating in ratings" :class="{'is-selected': ((value >= rating) && value != null), 'is-disabled': disabled}" @mouseover="star_over(rating)" @mouseout="star_out" @click="set(rating)"> <input class="star-rating star-rating__checkbox" type="radio" :name="name" :disabled="disabled" :id="id" :required="required" v-model="value"> ★ </label> </div> </template>

JS

'use strict'; Vue.component('star-rating', { template: '#template-star-rating', data: function data() { return { value: null, temp_value: null, ratings: [1, 2, 3, 4, 5] }; }, props: { 'name': String, 'value': null, 'id': String, 'disabled': Boolean, 'required': Boolean }, methods: { star_over: function star_over(index) { if (this.disabled) { return; } this.temp_value = this.value; this.value = index; }, star_out: function star_out() { if (this.disabled) { return; } this.value = this.temp_value; }, set: function set(value) { if (this.disabled) { return; } // This runs twice console.log(value); this.temp_value = value; this.value = value; } } }); new Vue({ el: '#star-app' });

The code is based on older version from someone, here it also doubles https://codepen.io/sktwentysix/pen/oZwXjN

Categories: Software

Vue.js server side rendering with axios

Vuejs - Thu, 2017-08-03 12:19

In a vue.js app with server side rendering, taking inspiration from the Vue Hn project and the vue ssr tutorial.

There is an /api/index.js file making the requests to an api which return a promise like specified here.

import data from './data' // just an a json object export function fetchList() { return new Promise((resolve, reject) => { if (true) { resolve(data) } else { reject('error') } }) }

So far so good, everything works fine: the page is server side rendered on first load and then things happen client side.

Now, I try to make a real api request with axios:

import axios from 'axios' const apiurl = `https://my-api.com/api/v1` export function fetchList() { // the api call works fine in postman return axios.get(`${apiurl}/posts`) .then(response => { return response.data }) .catch(error => { return error }) }

It does not working anymore:

  • the data are not fetched on the server (and not in the page on first load),
  • the first page load is really slow (10s or more)
  • after first page load, it still works fine client side…

Any idea on what is going wrong with this axios api call?

Categories: Software

Deleted values are removed only after page refresh in vue js

Vuejs - Thu, 2017-08-03 12:16

I need to delete the data in an id by using delete button, the values were got deleted but it was still displaying the values .. The deleted values were removed only after we doing a refresh of a page. How can i make the data gets deleted and removed from the table immediately after click event without doing page refresh?

Delete button:

<button class="btn btn-primary" v-on:click="deleteItems(booking.id)">Delete</button>

Script of delete:

methods: { deleteItems(id) { axios.delete(config.apiDomain+'/Booking/deleteItems/'+id).then((response)=>{ this.$router.push('/admin/booking'); console.log(id); }); }, }, mounted() { axios.get(config.apiDomain+'/Booking').then((response)=>this.items = response.data); }
Categories: Software

Pages