Vuejs

Subscribe to Vuejs feed
most recent 30 from stackoverflow.com 2017-09-14T21:10:11Z
Updated: 7 years 1 week ago

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

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

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

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

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

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

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

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

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

v-if not working on template tag

Tue, 2017-09-12 18:44

According to the Vue documentation I should be able to add the v-if condition to the <template> tag:

<template v-if="false"> <div>Invisible text</div> </template>

But this will not hide the element, but it does work when added to the child element:

<template> <div v-if="false">Invisible text</div> </template>

Any suggestions?

I'm including the template in another .vue file:

<template> <div id="app"> <H1 class= "main-title">Title</H1> <span class="components"> <testtemplate></testtemplate> </span> </div> </template>
Categories: Software

Content Security Polisy (CSP) - why I need 'unsafe-eval' rule?

Tue, 2017-09-12 18:28

I am trying to set CSP headers in my Vue 2.0 app and I have a problem with 'eval' policy.

When I use 'unsafe-eval' - it's all working fine. But when I get rid of it (I know I should) my scripts stop working. There is no error in console. But if I put eval() somewhere in my code intentionally - I get error in console.

I searched whole project (including libs) for "eval" and "new Function" but I can't find any usage of them.

So maybe there are some other functions which meet 'eval' rules? I am using Vue, but my code is built with Browserify + vueify.

Categories: Software

vuejs form computed property

Tue, 2017-09-12 18:13

I have a simple form in VueJS that I would like to have a computed property for one of the form fields. I would like the computed property to be calculated as the user inputs data and then saved as a data property before submitting the form to the server.

<form> <div> <h3>Revenue</h3> <input type="text" v-model="formData.revenue"> </div> <div> <h3>Expenses</h3> <input type="text" v-model="formData.expenses"> </div> <div> <h3>Operating Income</h3> <input type="text" v-model="formData.operatingIncome"> </div> </form>

JS

new Vue({ el: '#app', data: { formData: {} }, computed: { operatingIncome() { return this.formData.revenue - this.formData.expenses; } } });

The computed property for operatingIncome does not calculate unless I explicitly create properties for revenue and expenses within formData data object and change the to a string interpolation. Any suggestions on how to make this work?

Categories: Software

Show user-friendly error messages in Vue application

Tue, 2017-09-12 17:47

As with any application a number of things can go wrong sooner or later. I have a large Vue application that sometimes throws some errors (I know, it shouldn't, but sometimes it does anyway) and I'd like to show a friendly message to the user so they won't be stuck waiting. Like a "generic error handler" of some kind on the window object.

I tried this: javascript: how to display script errors in a popup alert? but it does not fire.

Any other suggestions?

Categories: Software

Vue values not recognized in template

Tue, 2017-09-12 17:42

Trying out Vue for the first time and having some problem with some values not beeing recognized in the template even though they are set when checking with the Chrome Vue debug tool.

I'm doing this in a Wordpress context if that matters, with an inline template. I stripped down a lot of non-important code in my example below to just focus on the loader. I'm setting the loading value to true and here I'm not changing it anywhere. When loading the page I can see the spinner briefly then it disappears. However the value of loading is true when I check with debug tool. What am I doing wrong?

Javascript:

(function($) { var employeesListingElement = document.getElementById('vue-employees-listing'); if ( employeesListingElement ) { var EmployeesListing = new Vue({ el : employeesListingElement, data() { return { employees: [], filter: '', errors: [], loading: true } } }); } })(jQuery);

PHP

<div id="vue-employees-listing"> <div v-if="employees.loading" class="ajax-loader"> <img src="<?php echo get_theme_file_uri('/spinner.svg'); ?>"> </div> </div>
Categories: Software

Update one of the multiple component's props in Vue.js from outside

Tue, 2017-09-12 17:40

Can't find a way to update a specific component's prop from outside of the component.

I have an App.js which loads all components in .vue format. What a basically do is I import a counter.vue inside the App.js, and want to modify one of the specific component's data.

Main file App.js:

Vue.component('counter', require('./components/Counter.vue')); export const App = window.App = new Vue({ el: '#app', methods: { } });

Here is a Counter.vue file:

<template> <span class="counter">{{ number }}</span> </template> <script> export default { props: ['name', 'number'], }; </script>

In my HTML I have multiple counter instances:

<counter name="cnameA" number="10"></counter> <counter name="cnameB" number="20"></counter> <counter name="cnameC" number="30"></counter>

How to I increment a counter with name cnameB by 1 ?

I tried to use a #watch approach, but it's not exactly what I need.

Categories: Software

Vue.js datepicker with vertically scrolling month/day/year

Tue, 2017-09-12 17:28

I saw an example datepicker for use with vue.js 2 a few days ago. The thing that was different about it was that when you click on the input box, instead of opening a calendar-type user interface, each part of the date (month, day, year) scrolled vertically. I think there was some animation, too. It looked really polished.

Spent all morning looking for it again, but I can't find it. Can someone please help me locate this component?

Categories: Software

How to fetch local html file with vue.js?

Tue, 2017-09-12 17:14

I am following this example

I am trying to load a html file with vue.js and add into my template.

my attempt:

HTTML:

<html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="/Static/content/css/foundation.css"> <link rel="stylesheet" type="text/css" href="/Static/content/css/spaceGame.css"> </head> <body> <div id="app"> <div class="grid-container"> <div class="grid-x grid-padding-x"> <div class="large-12 cell"> <h1>Welcome to Foundation</h1> </div> </div> </div> <div class="grid-x grid-padding-x"> <div class="large-4 columns"></div> <div class="large-8 columns"> <component :is="currentView"></component> </div> </div> </div> <!-- Footer --> <script src="https://unpkg.com/vue"></script> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="/Static/scripts/foundation.js"></script> <script type="text/javascript" src="/Static/scripts/what-input.js"></script> <script type="text/javascript" src="/Static/scripts/space.js"></script> </body> </html>

script:

$(function() { $(document).foundation() var myData = '../../Views/login.html'; Vue.component('manage-posts', { template: myData, }) Vue.component('create-post', { template: '#create-template' }) new Vue({ el: '#app', data: { currentView: 'manage-posts' } }) });

Errors:

above I get the following:

  • Component template requires a root element, rather than just text.

changing var myData = '../../Views/login.html';

to

var myData = '<div>../../Views/login.html</div>';

gets rid of that error but...how do I load the actual html file?

I am new to single page applications and to vue.js, been at this for some time now and can't figure it out.

Categories: Software

Vue.js Passing Data via httpVueLoader

Tue, 2017-09-12 17:09

I have a Vue instance.

var myApp = new Vue({ el: '#my-App', data: { user: sessionStorage.getItem('user') }, components: { 'header-component': httpVueLoader('./components/header-component.vue'), 'footer-component': httpVueLoader('./components/footer-component.vue') } });

And a single file component header-component

<template> <li v-if="user !== ''" class="nav-item"> <a class="nav-link" v-on:click="openProfilePage" href="#">{{user}}</a> </li> </template> <script> module.exports = { data: function () { return {} }, methods: { openProfilePage: function () { if (userName !== '') { myApp.page = 'profile'; sessionStorage.setItem('page', 'profile'); page = 'profile'; } else { myApp.page = 'login'; sessionStorage.setItem('page', 'login'); page = 'login'; } } } } </script>

I don't want to define a new data.user in my single file file component and i want to use the data.user of the vue instance. How can i do that? How can i pass this data?

Categories: Software

Vue.js - One-way data binding updating parent from child

Tue, 2017-09-12 16:12

Given that a colon indicates one-way-data-binding in VueJS2, I would like to understand why in this example, the child is able to update the array that was declared in the parent and passed to the child via prop (one-way).

https://jsfiddle.net/ecgxykrt/

<script src="https://unpkg.com/vue"></script> <div id="app"> <span>Parent value: {{ dataTest }}</span> <test :datatest="dataTest" /> </div> var test = { props: ['datatest'], mounted: function() { this.datatest.push(10) }, render: function() {} } new Vue({ el: '#app', components: { 'test': test }, data: function() { return { dataTest: [] } } })

Thanks in advance!

Categories: Software

v-model overwrite input value in VueJS

Tue, 2017-09-12 15:48

I have this input

<input type="text" :value="user.name" v-model="userInfo.name">

that is in a component edit.vue.

In users.vue I have router link

<router-link :to="'/users/edit-user/'+user.id"><a>Edit</a></router-link>

and when I click it takes me on edit component with the id of the actual user on url.

The problem is that if I put this v-model="userInfo.name" in that first input overwrites the data that I bring to edit it, the name.

If I delete this v-model="userInfo.name" from that input I can see the actual value of the input, that comes from database, I mean the actual name.

I need this v-model, in that edit page, to take the new input value and send it back to database.

In a normal edit, when you click on edit button, you suppose to see the actual data to edit it, not an empty input.

So why v-model overwrites that user.name value(that comes from a json users, from database) and what can I do to make a see the actual value and be able to send the modified value input in database?

Categories: Software

How to build a grid like this and zoom effet

Tue, 2017-09-12 14:58

i'm building a game that we use to play as kid on quadratic sheet, the idea is to encircle the other player dots like this image , i'm using vue.js and d3.js for javascript, i would like to do something like on this website , someone can tell me which technologies is used on that website and can also suggest the good one.

If someone know about this game tell me the name in english of that game

That you

Categories: Software

Pages