Software

Passing avatar link into vue js component but failed

Vuejs - Thu, 2017-08-17 06:29

I am new in vue js. Currently i am trying to passing data into vue js components. So far if i passing user name or other information is working fine. But if i passing the avatar link it will showing error in npm run watch. Any solution for this?

This is my code

<li v-for="comment in comments"> <div class="avatar"><img src="{{ comment.user.avatar }}" alt="" /></div> <div class="comment-content"><div class="arrow-comment"></div> <div class="comment-by">{{ comment.user.name }}<span class="date">22 August 2017</span> <a href="#" class="reply"><i class="fa fa-reply"></i> Reply</a> </div> <p>{{ comment.content }}</p> </div> </li>

enter image description here

This is the object i get.

Categories: Software

vue.js not working, getting a cannot read property of undefined error

Vuejs - Thu, 2017-08-17 02:54

I'm trying to v-model to an array item's property. When I load the page I see "[Vue warn]: Error in render function: 'TypeError: Cannot read property 'viewFood' of undefined' in the console and a blank page.

this is with vue.js 2.x.

https://codepen.io/jzaun/pen/YxYyJN/

html

<div id="ai-config"> <div class="info"> <div class="row"> <h1>Resource Points</h1> </div> <div class="row"> <label>Total:</label> <div class="value"> {{maxResourcePoints}} </div> </div> <div class="row"> <label>Remaining:</label> <div class="value"> {{maxResourcePoints - usedResourcePoints}} </div> </div> </div> <div> <table> <tr> <td></td> <td v-for="(option, idx) in options"> {{option.title}} </td> </tr> <tr v-for="n in directions"> <td>Direction {{n}}</td> <td v-for="option in options"> <input type="checkbox", v-model="selected[n][option.key]" /> </td> </tr> </table> </div> </div>

javascript

new Vue ({ el: '#ai-config', data: { maxResourcePoints: 10, usedResourcePoints: 0, selected: [], directions: 8, options: [{ title: 'Food', key: 'viewFood', cost: 1 }, { title: 'Water', key: 'viewWater', cost: 1 }, { title: 'Own', key: 'viewOwn', cost: 1 }, { title: 'Other', key: 'viewOther', cost: 1 }] }, methods: { }, created: function () { this.selected = []; for(i=0; i< 8; i++) { this.selected.push({}); } } });
Categories: Software

Trigger multiple methods on event and pass event variable

Vuejs - Thu, 2017-08-17 01:28

Using vue, I am trying to trigger multiple events on a click and pass 'event' variable, so that I can use event.target.

I tried this:

<element @click="onSubmit(), onChange()"></element>

And in my methods, I tried

methods: { onSubmit(e) { console.log(e) }, onChange(e) { console.log(e) } }

Cannot read property 'target' of undefined

What is the proper way of achieving this?

Categories: Software

Vue component :key context

Vuejs - Wed, 2017-08-16 23:51

In order to work with custom vue components in a v-for binding, the frameworks asks you to specify a key for each component.

The first thing that comes to my mind is using the index as key, i.e.

<MyComponent v-for="(i, data) in list" :key="i"></MyComponent>

So far so good, but how will Vue handle something like

<MyComponent v-for="(i, data) in list" :key="i"></MyComponent> <MyComponent v-for="(i, data) in list" :key="i"></MyComponent>

Do I need to keep track of making keys unique globally for all my MyComponent components? I.e. :key="i + 'scope1'", :key="i + 'scope2'" etc.

TL;DR: Will Vue mix up two components with the same key? Is it enough to make the keys unique for each loop context?

Categories: Software

How to pass data from one view to another with the vue-router

Vuejs - Wed, 2017-08-16 21:51

When using the vue-router with .vue files, there is no documented way to pass data from one view/component to another.

Let's take the following setup...

main.js:

import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); let routes = [ { path: '/page1', component: require('./views/Posts.vue') }, { path: '/page2', component: require('./views/EditPost.vue') } ]; let router = new VueRouter({ routes }); new Vue({ el: '#main', router });

Posts.vue:

<template> <div> Posts.vue passing the ID to EditPost.vue: {{ postId }} </div> </template> <script> export default { data() { return { allPostsHere: // Whatever... } } } </script>

EditPost.vue:

<template> <div> EditPost.vue received ID from Posts.vue: {{ receivedId }} </div> </template> <script> export default { data() { return { receivedId: // This is where I need the ID from Posts.vue } } } </script>

Please note: It is not possible to receive the ID directly from the EditPost.vue, because it has to be selected from Posts.vue.

Question: How can I pass the ID from one view/component to the other?

Categories: Software

How to add dynamiclly VueJS component to packery?

Vuejs - Wed, 2017-08-16 21:49

Hi I got a problem with packery.

Based on this solution https://codepen.io/Monocle/pen/ZbeBGL

I have every grid-item as a component and then in app.js (main file) im initializing packery based on example given.

var pckry = new Packery(container, { itemSelector: '.grid-item', columnWidth: '.grid-sizer', });

I want now to handle turn on/off components and then making them draggabilly and bind/unbind to packery. But the problem is I cant make packery as an attrbute of vue object and just make this.pckry.getShiftPositions() (based on example: https://codepen.io/desandro/pen/PZrXVv).

pckry.on( 'dragItemPositioned', function() { // save drag positions var positions = pckry.getShiftPositions( 'data-item-id' ); localStorage.setItem( 'dragPositions', JSON.stringify( positions ) ); });

The problem is with handling instance of packery object I guess. its just not working.

this.pckry.on( 'dragItemPositioned', function() { // save drag positions var positions = this.pckry.getShiftPositions( 'data-item-id' ); localStorage.setItem( 'dragPositions', JSON.stringify( positions ) ); });

Doesnt actually work. When im making it as

this.pckry = newPackery(...);

How can I actually handle that?

Categories: Software

How to dynamically create a new div using v-for in Vue.js?

Vuejs - Wed, 2017-08-16 20:20

I want to create div's dynamically based on the number of elements present in an array. The div's contain the html element created by ProgressBar.js.

This the Vue.js code

import ProgressBar from 'progressbar.js' var bar; export default { data() { return { fitness: ['Dietary Intake', 'Exercise'], val: 0.65 } }, mounted(){ this.showProgressBar(this.val); }, created: function() { }, methods:{ showProgressBar: function(val){ new ProgressBar.Circle('#container',{ trailColor: 'gainsboro', trailWidth: 20, color: 'teal', strokeWidth: 20 }).animate(val); } } } <div class="content" v-for="fitness in fitness"> <span>{{ fitness }}</span> <div id="container"></div> </div> I am trying to get done something like this,

enter image description here

Since an id is associated with only one div, I am not able to execute a new ProgressBar.Circle object that would create another div. Is there a way to dynamically create a new div with different a id inside the v-for every time the new ProgressBar.circle is executed? Can somenone please help me out here?

Categories: Software

Vuejs transition on table rows

Vuejs - Wed, 2017-08-16 19:57

I'm tring to have an transition (animation) on html table row with vue.js with no success here the full example https://jsfiddle.net/c8vqajb4/

here the basic html table :

<div class="container-fluid" id="data"> <br> <br> <table border="1" class="table table-bordered"> <thead class="thead-inverse"> <tr> <th>anim</th> </tr> </thead> <tbody> <template v-for="item, k in items"> <tr> <td><button @click="item.more = !item.more" type="button" v-bind:class="[item.more ? 'btn-danger' : 'btn-primary']" class="btn">Click /!\</button></td> </tr> <transition name="fade" > <tr v-bind:key="item" v-if="item.more"> <td><p >{{k + 1}} - {{item.data}}</p></td> </tr> </transition> </template> </tbody> </table> </div>

the css for the transition:

.fade-enter-active, .fade-leave-active { transition: opacity 2s } .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ { opacity: 0 }

the vuejs code:

(function () { new Vue({ el: '#data', data: { items: [ { data: 'd1', more: false }, { data: 'd2', more: false }, ] } }); })();

what i'm doing wrong ?

Categories: Software

Nested array loop in vue?

Vuejs - Wed, 2017-08-16 19:54

How would I loop a JSON object like the one below with v-for? I want to loop all ID's/Numbers, and all items in inside each number, and display it all in a list... I know I can loop all system_events easily using v-for="item in system_events" But how do I loop all different ID's/Numbers, and all items inside ?

My JSON looks like:

{ "system_events": { "1013": [{ "id": 25899, "timestamp": "2017-08-15T21:26:42Z", "type": "alarm", "code": 190, "title": "", "description": "", "appeared": "2017-08-15T21:26:40Z", "disappeared": null, "acknowlegded": null, "solved": null, "system_name": "Randers pr 44b sidste station" }, { "id": 26157, "timestamp": "2017-08-15T21:32:17Z", "type": "alarm", "code": 190, "title": "", "description": "", "appeared": "2017-08-15T21:32:06Z", "disappeared": null, "acknowlegded": null, "solved": null, "system_name": "Randers pr 44b sidste station" } ], "1015": [{ "id": 23777, "timestamp": "2017-08-15T20:38:08Z", "type": "alarm", "code": 191, "title": "", "description": "", "appeared": "2017-08-15T20:38:00Z", "disappeared": null, "acknowlegded": null, "solved": null, "system_name": "Favrskov Svenstrup gyvelvej" }, { "id": 23779, "timestamp": "2017-08-15T20:38:08Z", "type": "alarm", "code": 190, "title": "", "description": "", "appeared": "2017-08-15T20:37:58Z", "disappeared": null, "acknowlegded": null, "solved": null, "system_name": "Favrskov Svenstrup gyvelvej" } ] } }
Categories: Software

Calling a new Vue on router-view to display a list

Vuejs - Wed, 2017-08-16 18:28

I am trying to write a simple single page application with Vue to gain an understanding of it's capabilities. This simple application will display a list of acronyms, then the user can click a link and be given details about that acronym. I am using vue-router to manage the routes. My basic app div is like below:

<div id="app"> <h1>Hello App!</h1> <p> <router-link to="/">Home</router-link> <router-link to="/acronyms">All Acronyms</router-link> </p> <router-view></router-view> </div>

I first create a template to list all the acronyms:

const AllAcronyms = {template: '<div><ul id="all-acronyms"><li v-for="acronym in acronyms">{{ acronym.id }} - {{acronym.abbreviation}}</li></ul></div>' };

Then I create the router, routes, and the Vue:

var routes = [ { path: '/acronyms', component: AllAcronyms } ]; var router = new VueRouter({ routes: routes }); var view = new Vue({ el: "#app", data: { acronyms: [ { id: 1, abbreviation: "ABC" }, { id: 2, abbreviation: "DEF" }, { id: 3, abbreviation: "GHI" } ] }, router: router });

It tells me that "acronyms" is undefined. Is there a way to use the v-for directive on a router view by passing the data to that route, or to create a new Vue object on the "all-acronyms" unordered list when the route is called? What is the best way to go about this?

Categories: Software

Vue 2 component prop getting wrong value

Vuejs - Wed, 2017-08-16 18:22

I am trying to build a menu between categories. If a category has a sub-category it returns a value that says has_subCategory as boolean 0/1.

<template> <select><slot></slot></select> </template> <script> export default { props: ['value', 'hasSubCat'], watch: { value: function(value, hasSubCat) { this.relaod(value); this.fetchSubCategories(value, hasSubCat); } }, methods: { relaod: function(value) { var select = $(this.$el); select.val(value || this.value); select.material_select('destroy'); select.material_select(); }, fetchSubCategories: function(value, hasSubCat) { var mdl = this; var catID = value || this.value; var has_subCat = hasSubCat || this.hasSubCat; console.log("has_subCat:" + hasSubCat); mdl.$emit("reset-subcats"); if (catID) { if (has_subCat == 0) { if ($('.subdropdown').is(":visible") == true) { $('.subdropdown').fadeOut(); } } else { axios.get(URL.API + '/subcategories/' + catID) .then(function(response) { response = response.data.subcatData; response.unshift({ subcat_id: '0', subcategory_name: 'All Subcategories' }); mdl.$emit("update-subcats", response); $('.subdropdown').fadeIn(); }) .catch(function(error) { if (error.response.data) { swal({ title: "Something went wrong", text: "Please try again", type: "error", html: false }); } }); } } else { if ($('.subdropdown').is(":visible") == true) { $('.subdropdown').fadeOut(); } } } }, mounted: function() { var vm = this; var select = $(this.$el); select .val(this.value) .on('change', function() { vm.$emit('input', this.value); }); select.material_select(); }, updated: function() { this.relaod(); }, destroyed: function() { $(this.$el).material_select('destroy'); } } </script>

What I dont understand is that console.log("has_subCat:" + hasSubCat); prints out different values each time I change the select. It should only display 0 or 1

Categories: Software

VueJS return loop data values through a node plugin

Vuejs - Wed, 2017-08-16 18:16

Hi I'm trying to create an Vue app which takes one key color and creates a color palette from the key color. 2 colors lighter and 2 colors darker. I have an input field where you enter a hex code and it will then generate the other 4 colours. I'm using the library chroma.js to generate darker/brighter colors and the syntax looks like this:

chroma('red').darken(.4)

And this is the input field

<input class="w-100 pv3 pl4 input-reset ba b--black-20" @keyup="getColor(colorValue)" v-model="colorValue" placeholder="0AD674" >

This is my for loop

<li v-for="item in items"> {{ item.colorProperty }} {{ item.intensity }} {{ colorValue }} </li>

And my data inside the Vue instance.

data () { return { colorValue: '4e35e1', items: [ { intensity: 3, colorProperty: 'darken' }, { intensity: 1, colorProperty: 'darken' }, { intensity: 0, colorProperty: '' }, { intensity: 1, colorProperty: 'brighten' }, { intensity: 3, colorProperty: 'brighten' } ], } }

All of this generates something like

3 darken 4e35e1 1 darken 4e35e1 0 4e35e1 1 brighten 4e35e1 3 brighten 4e35e1

Which is cool but ideally I would use the data values to feed the Chroma.js syntax like

transformColor: function(value, property, intensity) { return chroma(value).property(intensity) }

But obviously that doesn't work. What's the best way to achieve this?

I realise this is a open ended question. But I have had troubles figuring out whether I should use a filter or a component or a computed function. I tried most things but none of them would work. I come from a jQuery background so this new data-centric approach is proving to be difficult to wrap my head around. I'm grateful for any pointers!

Categories: Software

Vue Webpack template's E2E does not work on a headless box

Vuejs - Wed, 2017-08-16 18:02

With the vue-cli webpack template... has anyone gotten npm run e2e to work on a headless box? I've tried running it in docker's node:latest and under elgalu/docker-selenium both times I get this cryptic error

Starting selenium server... started - PID: 6621 [Test] Test Suite ===================== Running: default e2e tests Error retrieving a new session from the selenium server Connection refused! Is selenium server started? { state: 'unknown error', sessionId: null, hCode: 648061585, value: { localizedMessage: null, cause: null, suppressed: [], message: null, hCode: 1628902597, class: 'java.util.concurrent.TimeoutException', screen: null }, class: 'org.openqa.selenium.remote.Response', status: 13 } npm ERR! Linux 4.9.36-moby npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "run" "e2e" npm ERR! node v6.11.2 npm ERR! npm v3.10.10 npm ERR! code ELIFECYCLE npm ERR! learn-web@1.0.0 e2e: `node test/e2e/runner.js` npm ERR! Exit status 1
Categories: Software

VueJS,vue-form-generator Accessing $store from field callback

Vuejs - Wed, 2017-08-16 17:44

I am using the vue-form-generator component. I am attempting to update a variable in the store with the response from a call back. What I believe the relevant code is (inside the schema:fields property):

{ type: 'submit', buttonText: 'Save Updates', styleClasses: ['custom-submit', 'custom-submit-primary', 'custom-submit-full'], disabled () { return this.errors.length > 0 }, validateBeforeSubmit: true, onSubmit: function (model, schema) { Vue.CustomSubmit('UserUpdate', model).then((response) => { this.$store.user = response }) } }

From within the Vue.CustomSubmit().then((response)) => { ... } I don't seem to be able to access the store.

It works slightly higher in scope, such as:

data () { return { avatar: this.$store.getters.user.avatar, ... }
Categories: Software

framework7 issue with a accordion

Vuejs - Wed, 2017-08-16 17:42

i am using framework7 last version , and my app hierarchy is like that :

vue router-view , vue children are loaded within router-view , one of those children is the root of framework7 app , when i navigate between "the root of framework7 which is a component" and any other component , the accordion animation start to stuck and act unexpectedly but it works good before navigation done .

i try to reset everything here with in the vue component which acts as root

export default { data() { return { appIsRdy: false } }, mounted() { this.$store.state.f7.f7Obj = new Framework7({ root: '.f7root' }); this.$store.state.f7.$$ = Dom7; this.$store.state.f7.mView = this.$store.state.f7.f7Obj.addView('.view-main', { domCache: true }); this.appIsRdy = true; }, components: { MainPage, RedditPage }, beforeDestroy() { this.$store.state.f7.f7Obj = null; this.$store.state.f7.$$ = null; this.$store.state.f7.mView = null; this.appIsRdy = false; } }
Categories: Software

How connect with server on client side with Vue.js, Socket.io, Arduino?

Vuejs - Wed, 2017-08-16 17:40

I have a problem with connection server by client application. I want to connect with my arduino board and control by client side wriiten in vue.js.

I have a server who run on node.js, and run good.

const http = require('http'); const socketIo = require('socket.io'); const port = process.env.PORT || 5000; const server = http.createServer().listen(port, () => { }); const five = require('johnny-five'); const board = new five.Board(); const pin = { 13: { led: { on: () => console.log('on'), off: () => console.log('off'), }, }, }; const io = socketIo(server); board.on('ready', () => { const led = new five.Led(13); led.off(); pin[13].led = led; }); io.sockets.on('connection', (socket) => { socket.on('message', (channel, message) => { if (channel === 'on') pin[message].led.on(); if (channel === 'off') pin[message].led.blink(500); }); });

but i have a problem with client-side. This is my code, and i don't know what can i do now.

<template> <router-view> </router-view> </template> <script> import Vue from 'vue'; import VueRouter from 'vue-router/dist/vue-router'; import LoginRoutes from 'features/login/login.routes'; import FoobarRoutes from 'features/foobar/foobar.routes'; import 'common/components'; import Jquery from 'jquery'; import BootstrapCSS from 'bootstrap/dist/css/bootstrap.css'; import Bootstrap from 'bootstrap'; Vue.use(VueRouter); io = require("socket.io/lib/socket"); var socket = io.connect("http://localhost:5000"); const routes = [ { path: '/', redirect() { return '/login'; }, }, ...LoginRoutes, ...FoobarRoutes, ]; const router = new VueRouter({ routes, }); export default { router, }; </script>

and this is my view :

<template> <div> <h1>TURN ON/OFF LED</h1> <button class="btn btn-danger" @click='on'>13: ON</button> <br><br> <button @click='off'>13: OFF</button> </div> </template> <script> export default { name: 'login-view', methods: { on: function() { socket.send('on', 13); // this.$socket.emit('on', 13); }, off: function() { socket.send('off', 13); }, }, }; </script> <style> </style>
Categories: Software

variable inside watch not reactive vuejs

Vuejs - Wed, 2017-08-16 16:27

I am watching an array and if some conditions met I want to disable / modify other elements but no luck so far, as the variable already_answered is not reactive.

<input :disabled="already_answered" type="text" /> data: function() { return { already_answered: false, somearr: [], }; }, watch: { somearr() { for (var i = 0; i < this.somearr.length; i++) { if (this.somearr[i]["id"] == 5) { this.already_answered = true break; } } }, },
Categories: Software

How insert one-to-many

Vuejs - Wed, 2017-08-16 16:22

There is a database with two tables (recipe, flavor). Between them one-to-many relationships one recipe is a lot of flavors. I add data through the put vue method

saverecipe: function(){ this.$http.put('/recipe/new', this.newrecipe).then(function (data) { console.log(this.newrecipe) }) }

Google Chrome data example with one flavor

handler

func PutRecipe(db *sql.DB) echo.HandlerFunc { return func(c echo.Context) error { var recipe models.Recipe c.Bind(&recipe) id, err := models.PutRecipe(db, recipe.RECIPENAME, recipe.BOTTLEID, recipe.BOTTLESIZE, recipe.PG, recipe.VG, recipe.NICOTINE, recipe.DATE, recipe.NOTE, recipe.FLAVORID, recipe.NAME, recipe.DROPS, recipe.RECIPEID) if err == nil { return c.JSON(http.StatusCreated, H{ "created": id, }) } else { log.Fatal(err) return err } } }

model

func PutRecipe(db *sql.DB, recipename string, bottleID int, bottlesize int, pg int, vg int, nicotine int, date string, note string, flavorid int, name string, drops int, recipeid int) (int64, error) { sql := `INSERT INTO recipe(recipename, bottleID, bottlesize, pg, vg, nicotine, date, note, flavorid) VALUES(?,?,?,?,?,?,?,?,?,?,?,?); INSERT INTO flavor(name, drops, recipeid) VALUES(?,?,?)` stmt, err := db.Prepare(sql) if err != nil { log.Fatal(err) } defer stmt.Close() result, err2 := stmt.Exec(recipename, bottleID, bottlesize, pg, vg, nicotine, date, note, flavorid, name, drops, recipeid) if err2 != nil { log.Fatal(err2) } return result.LastInsertId() }

Data must be written in two tables. One is a recipe. One - flavor. How can I do that? If you need I can lay out all the code on the github

Categories: Software

Lazy loading images in Vue/Laravel

Vuejs - Wed, 2017-08-16 16:18

I am trying to use jQuery Lazy Loading in my Laravel/Vue project but I am struggling to get an image to appear in my Vue component. I have the following img block which I thought would work:

<img v-if="vehicle.photo_path != null" :data-original="'/storage/vehicles/' + vehicle.photo_path" class="lazy" height="180" width="150"/>

I did find this other question on here - Static image src in Vue.js template - however when I try that method I get this: Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead.

So I switched back to the v-bind method but all I am getting is a white box with a grey border - no image. If I v-bind on the src attribute however I can see the image correctly.

I know I have implemented the Lazy Loading plugin correctly as I can successfully call it elsewhere on my site (such as on a blade view), but I'm not sure where I am going wrong. Thank you.

Categories: Software

Pages