Software

sorting list of object by property in VueJS

Vuejs - Mon, 2017-08-21 04:10

I have just started to learn VueJS 2 and the more questions I have the harder it becomes.

The idea is that I have a sample problem with an array of objects, where I want to sort the array by "votes" property, which can be dynamically updated for each separate element. I want to sort my list by votes dynamically. Thus the question is how can I do that without doing weird code.

In angular you will do something like

for candidate in candidates | orderBy: 'votes'

but in here I could of though only of something like

v-for="(value, index, key) in sorted_candidates"

where in .js I'll have

computed : { sorted_candidates() { return this.candidates.sort((a, b) => { return b.votes - a.votes;}); } }

So my question would be if there is a more elegant way to solve this problem? Note: I am sorting on object property.

Categories: Software

How to add custom styles to material components without breaking anything

Vuejs - Sun, 2017-08-20 23:56

I am using vuejs with vuetify a material design support for vuejs, but I am confused as to how I can add custom css styles to material design without breaking a convention of the material design itself.

It is like bootstrap where we can call .row{} and override the styling or does it differ in some ways.

Categories: Software

Looping over parent data (set via Ajax) in child components

Vuejs - Sun, 2017-08-20 22:28

How can I loop over data set via ajax in my component methods? The problem is that when I try to call a method to perform the loop on component mounted(), the data isn't there yet. How can I tell my vue component to wait for the ajax data to arrive to execute the function? The parent makes the ajax call, so I can't stick it in the .done() function.

Vue.component('sidebar', { props: ['people'], template: ` <div id="sidebarContain" v-if="this.people"> <div v-for="person in people" :class="[{'checked-in': isCheckedIn(person)}, 'person']" :id="person.id"> {{person.first_name + ' ' + person.last_name}} </div> </div> `, methods: { isCheckedIn(person) { return person.reg_scan == null ? true : false; }, displayName() { //this is the function I want to run when ajax data is done and passed from parent to child for (var i = 0; i < this.people.length; i++) { console.log(this.people[i]); } } }, mounted() { this.displayName(); } }); var app = new Vue({ el: '#main', data: { people: [] }, methods: { loadPeople() { $.ajax({ method: 'POST', dataType: 'json', url: base_url + 'users/getParticipants/' + event_id }).done(data => { this.people = data; }); }, setRefresh() { setInterval(() => { console.log("Getting People"); this.loadPeople(); }, 10000); } }, mounted() { this.loadPeople(); this.setRefresh(); } }); <div id="app"> <sidebar :people="people"></sidebar> </div>

Categories: Software

Leveraging the v-for loop for places outside the v-for

Vuejs - Sun, 2017-08-20 21:58

While looping on array of sales , i need to capture the object of which salesPerson === "bar" and print its sellValue outside the v-for block.

Of course i can't access the array in hard-coded way. i have to assume that the position of the object i'm looking for is random.

also, i can't add another loop on top of the one loop that already exist here. (v-for is a loop obviously).

i need way to do achieve it.

here is an example component:

<template> <div id="app"> <!-- i need to print here the sellValue of 'bar' --> <p v-for="(sell,index) in sales" :key="index">{{sell.sellValue}}</p> </div> </template> <script> export default { name: 'app', data() { return { sales: [ { salesPerson: 'foo', sellValue: 1 }, { salesPerson: 'bar', sellValue: 2 } ] } } } </script>
Categories: Software

install vuejs-uib-pagination plugin for Vue.js on laravel 5.4

Vuejs - Sun, 2017-08-20 21:39

I'm trying to install vuejs-uib-pagination on laravel 5.4... (https://github.com/sant123/vuejs-uib-pagination)

  1. npm install vuejs-uib-pagination
  2. Added the following codes to /resources/assets/js/app.js

  3. npm run dev

  4. Added HTML and scripts

On browser, I got an error: [Vue warn]: Unknown custom element: <uib-pagination> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

Some codes located at /src/types/index.ts like Vue.component("uib-pagination",...

I think I need to import these stuffs, but I'm not familiar with 'webpack' or 'mix'. Where will be the proper way to import the codes?

Categories: Software

Vue.js check if scroller scrolled to the element

Vuejs - Sun, 2017-08-20 21:15

I have an element in my html code

<div class="my_div"> </div>

Now i want to alert when user scrolled to this element.How can i do that using Vue considering that my_div is in the center of the page?

Categories: Software

(Vue) Inject variable into all components

Vuejs - Sun, 2017-08-20 21:06

I have a global status variable, STATUS, that I'd like to inject into essentially all of my Vue components, given so many of them have to test against the status of API calls.

Two questions:

  1. Does this kind of go against a Vue paradigm, and I should find a different solution?
  2. If not, what is the best way to do this (add to window, etc...)?
Categories: Software

Web Push Notification FCM on Mobile

Vuejs - Sun, 2017-08-20 20:29

I'm trying to send push notification to users in my Web App but it is not working on mobile.

I'm using VueJs + Firebase, i use a Cloud Function to send the notification and in the service worker i receive and handle for show to the user.

It work in the Browser on PC, but dont work in mobile 'Android', here are some code:

Cloud Function:

}).then(function (aTokens) { const payload = { data: { title: 'Test-Title', body: 'Test-Body' } } // Send notifications to all tokens. return admin.messaging().sendToDevice(aTokens, payload).then(res => { res.results.forEach((result, index) => { const error = result.error if (error) { console.error('Failure sending notification to', tokens[index], error) } }) response.send('OK') }) })

Service-Worker Function:

importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase- messaging.js'); var config = { messagingSenderId: "1033425324523" } firebase.initializeApp(config); var messaging = firebase.messaging(); messaging.setBackgroundMessageHandler(function (payload) { var title = payload.data.title; var options = { body: payload.data.body }; return self.registration.showNotification(title, options); });

In Browser the Notification work See The Image:

But in Android it dont work, i have the last version or chrome and firefox and i tested in both, i also put the Web app in the home screen and allowed to send notification too. But the notifications nerver show there.

What i need to include for i see push notifications on mobile too?

Categories: Software

Vue.js SSR - how to require vue-server-renderer with import instead?

Vuejs - Sun, 2017-08-20 19:55

How can I require vue-server-renderer with import instead?

const renderer = require('vue-server-renderer').createRenderer()

I tried:

import renderer from 'vue-server-renderer' const vueRenderer = renderer.createRenderer()

Error:

var vueRenderer = _vueServerRenderer2.default.createRenderer(); ^ TypeError: Cannot read property 'createRenderer' of undefined

Any ideas?

Categories: Software

Hide menu vue.js 2.0 when clicked on router-link max-width: 767px

Vuejs - Sun, 2017-08-20 16:40

Trying to build a dropdown-menu that will only be shown when screen is smaller than 767px. There are two requirements here to hide the menu and those are:

If someone clicks outside the menu and when a random router link is being clicked.

export default { name: 'navbar', data() { return { isShow: false } }, methods: { onClick(e) { isShow = false } } } <button v-on:click ="isShow = !isShow">Click ME</button> <div class="router" v-show="isShow"> <router-link to="/" class="nav-link" @click.native="onClick">Home</router-link> <router-link to="/phones" class="nav-link">Phones</router-link> <router-link to="/moreproducts" class="nav-link">More Products</router-link> <router-link to="/blogs" class="nav-link">Support</router-link> <router-link to="/news" class="nav-link">News</router-link> </div> </div>

Categories: Software

How can I make vuefire show loading screen?

Vuejs - Sun, 2017-08-20 16:05

As title Vuefire can auto get data from firebase database, but it needs some loading time. So I want to display some css animation before data being fetched, is there any event can I $watch when it successed

Categories: Software

Move Vue JS project from localhost to a public server

Vuejs - Sun, 2017-08-20 11:35

I just finished a basic project in Vue JS, on my localhost server. Now, what I want to do is to move all the content from localhost to a public server. What can I do to solve this problem?

Categories: Software

Show gist scripts in Vue js

Vuejs - Sun, 2017-08-20 10:55

I am working with a Vue-js based website and showing data using JSON API. I parse data using Axios and returned the response to my view.

My JSON API contains some HTML data including an embed gist like below

<p>Some informative text here <br /> <script src="https://gist.github.com/nisat19/8e8e2c03ecbf198daef168948548d481.js"></script> </p>

In the view, I tried to render my data with v-html

<div v-html="content"></div>

It successfully parses only the HTML portion but does not render the gist. i.e

Some informative text here /* Gist Script Missing */

Is there any way to parse the script?

Categories: Software

Better way to create a web application with Java and Vue

Vuejs - Sun, 2017-08-20 07:18

I'm starting to get into web development a little more. Currently I use the Spark Framework along with Vue for the few apps I've made. While this certainly works it's not ideal.

The project is built with Maven (and NPM for Vue) and the build process looks something like this.

  1. Maven packages the Spark Framework Java application
  2. Maven (with the frontend-maven-plugin) downloads node/npm and builds the Vue frontend
  3. Maven copies the compiled resources into the jar as static assets

So the filesystem looks something like this

/src/main/java (Spark Framework)

/src/main/resources (Vue)

This leads to a couple of annoyances.

  1. Everything is in one repository. Ideally I'd be able to have a separate repo for each project
  2. Development workflow isn't ideal. If I just want to test the Java part of the app, I still spend time compiling the frontend (Vue)
  3. A minor issue, but while working in an IDE, I'm dealing with deeply nested folders. Anytime I want to edit the frontend, my folder structure looks something like /src/main/resources/project-vue/

Here's one of my projects that uses this model

So my question is: What's a better way to structure my application?

Categories: Software

how to get the component instance within an @click event?

Vuejs - Sun, 2017-08-20 05:43

I have a button in a Vue component

<el-button class='range-right' @click='deleteItem(item)'>delete</el-button>

within it's handler I want to invoke other methods of the component. however, even though I can call deleteItem which is itself a component method, I cannot get at the actual component for other methods.

is there a way to pass something like a $component param to the @click event?

methods { deleteItem: (item, obj) => { let api = '/api/train/deleteItem?_id=' + item._id let resource = Vue.resource(api) let vm = this // NOT a component window.delItem = this console.log('deleteItem.this', this) resource.delete(api) .then(items => { console.log('deleted') vm.methods.load() //<< fails }) },
Categories: Software

Update nav bar links to active and smooth scrolling

Vuejs - Sun, 2017-08-20 05:11

I am trying to implement a nav bar with list of <a> tag to navigate to different part of the current page and the tag should change class to active when the user is scrolling through the page.

Not sure what is the best way to implement it on a Vue app but I do not want to use bootstrap with jquery on it.

I found a framework agnostic library: https://github.com/cferdinandi/gumshoe and smooth scrolling now works, but the anchor tags are not being set to active. Tried a couple of other libraries to implement the updating of active but to no avail.

So I am not sure if I am setting those external libraries correctly in Vue.

What I did was include this in my index.html

<body> <div id="app"></div> <!-- built files will be auto injected --> <script src="static/js/gumshoe.js"> </script> <script src="static/js/smooth-scroll.min.js"> </script> <script> smoothScroll.init({ offset: 20 }); gumshoe.init(); </script> <script src="static/js/scroll-spy.js"> </script> </body>

Usage

<ul class="nav-right-items" data-gumshoe> <li class=""> <a data-scroll data-scroll-spy href="#about" class="">About me </a> </li> <li class=""> <a data-scroll data-scroll-spy href="#experience" class="">Experience </a> </li> </ul>
Categories: Software

Vue router-link exact active class

Vuejs - Sun, 2017-08-20 04:36

I have a 3 of menu tabs (i.e. router-links) that correspond to 3 different routes:

/ --> home /users --> users /posts --> posts

The first router-link going to / has the exact property applied, so it does not receive an active class when on /users or /posts. This works for most cases, however I am planning on allowing query parameters on the / route. For example:

/?ref=producthunt

In this case, the / router-link should still be active. However, given I have the exact property on it, it is not matching the url with the ref query parameter. Outside of adding additional logic to my component to test the route and flip classes, is there some feature of the router-link component I can use to solve this?

Categories: Software

Vue App structuring

Vuejs - Sun, 2017-08-20 02:44

I am currently trying to build my first webapp using vue.js

Now 2 days of tutorials deep I am still not 100% sure how to structure a basic application. Using the vue-cli and webpack already makes a nice structure, including a /src Folder with components and a /router Folder for routing.

Now my plan is to create a ToDo App. I want to dynamically switch between [show todos] and [add todo], which is just a form with a submit button. I have already achieved it by using it without components and the cli.

My structure would be:

App.vue -> buttons with the two router-link to components/ShowTodos.vue & components/AddTodos.vue

components/ShowTodos.vue -> Table including the todo list

components/AddTodos.vue -> Form with submit button

Now the routing part works, I am able to switch between those two components.

Now 2 Questions:

  1. How can I push the information from the form in the AddTodos component into an Array in the ShowTodos component in order to loop through there ?
  2. Is this a proper way to structure an vue app, and if not how can I improve it ?

    Thank you very much.

This is the first time for me using a component based JS Framework, so its pretty hard to follow along.

enter image description here

Categories: Software

VueJS - Why "this" is being used in this case?

Vuejs - Sun, 2017-08-20 01:23

I'm learning VueJS and I figure out the usage of "this" in some cases. By example: to access some atribute in the data().

But, I tried to call a method inside another method and was doing nothing because I wasn't using "this" to call the other method. Can someone explain the more detailed the general and in this case usage of "this"?

methods:{ sendData(){ this.$http.post('FIREBASE-LINK/data.json', this.user).then(response=>{ console.log(response) this.getData() }).catch(err=>{ console.log(err) }) }, getData: function () { this.$http.get('FIREBASE-LINK/data.json').then(resp=>{ this.users = resp.body }).catch(err=>{ console.log(err) }) } }
Categories: Software

Vue + Typescript + Webpack: Module build failing - Can't find vue.esm.js

Vuejs - Sun, 2017-08-20 00:06

I am trying to build a basic project using typescript, webpack and vue.js. However, when i run webpack from the command line, I am currently getting the following error:

ERROR in ./node_modules/vue/dist/vue.esm.js Module build failed: Error: Could not find file: 'c:\Users\user\Games\javascriptTimeGame\node_modules\vue\dist\vue.esm.js'. at getValidSourceFile (c:\Users\user\Games\javascriptTimeGame\node_modules\typescript\lib\typescript.js:89078:23) at Object.getEmitOutput (c:\Users\user\Games\javascriptTimeGame\node_modules\typescript\lib\typescript.js:89448:30) at getEmit (c:\Users\user\Games\javascriptTimeGame\node_modules\ts-loader\dist\index.js:122:43) at successLoader (c:\Users\user\Games\javascriptTimeGame\node_modules\ts-loader\dist\index.js:42:11) at Object.loader (c:\Users\user\Games\javascriptTimeGame\node_modules\ts-loader\dist\index.js:29:12)

This is strange, because the file it says it can't find is definitely there.

My main script: script.ts, looks like:

import Vue from 'vue' function main(){ let vueApp = new Vue({ el: "#vue-test", data : { message: "Hello World" } }); } main();

My tsconfig.json looks like:

{ "compileOnSave": true, "compilerOptions": { "target": "es6", "module": "es6", "moduleResolution": "node", "allowSyntheticDefaultImports": true, "strict": true, "removeComments": true, "preserveConstEnums": true, "sourceMap": true, "outDir": "../jsDist", "allowJs": true } }

My package.json dev dependencies look like:

"devDependencies": { "@types/vue": "^2.0.0", "http-server": "^0.10.0", "node-sass": "^4.5.3", "npm-run-all": "^4.0.2", "ts-loader": "^2.3.3", "typescript": "^2.4.2", "vue": "^2.4.2", "watch": "^1.0.2", "webpack": "^3.5.5" } }

And my webpack.config.js looks like:

module.exports = { devtool: 'inline-source-map', entry: "./ts/script.ts", output: { filename: "bundle.js", path: `${__dirname}/jsDist` }, module: { rules : [ { loader: 'ts-loader' } ] }, resolve: { extensions: ['.ts', '.js'], alias: { 'vue$': 'vue/dist/vue.esm.js' }, } }

A few things I've noticed that might isolate the problem.

First, If I simply run tsc to directly build my source files with the typescript compiler, then it works perfectly without error. This suggests there is something wrong with the webpack part specifically.

Second, If I alter script.ts to just be:

import Vue from 'vue' function main(){ console.log("Harmless"); } main();

Then webpack builds it without fuss. This suggests that it is not the top-line import that webpack seems to have a problem with, but specifically the usage of Vue.

Finally if I alter my webpack.config.js such that ts-loader has the additional option transpileOnly: true then it also seems to build without fuss (but of course I don't want to do this, as then I lose my reason for using typescript in the first place!)

Any ideas what might be causing this error?

Categories: Software

Pages