Vuejs

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

Vue client-side hydration

Mon, 2017-08-28 08:49

I am wondering where it possible to find out if vue client-side was hydrated or not?

Of cource, my server app has provided a valid html to the client corresponded this docs https://ssr.vuejs.org/en/hydration.html
Example:
<div id="app" data-server-rendered="true"> ... </div>

Somebody knows?

Thanks.

Categories: Software

Vue JS2 parent and child checkboxes

Mon, 2017-08-28 07:16

I have a list of lists:

<ul> <li v-for="subregion in continents"> <input type="checkbox" :id="subregion[0].subregion" > <label :for="subregion[0].subregion">{{ subregion[0].subregion }}</label> <ul> <li v-for="country of subregion"> <input type="checkbox" :id="country.name" > <label :for="country.name">{{ country.name }} (+{{ country.callingCodes[0]}})</label> </li> </ul> </li> </ul> Full code here: https://jsfiddle.net/kw1vmvqy/

How do I implement a method so when I check/uncheck a continent check box it checks/unchecks all the country check boxes in it? Also if I uncheck one country check box - it unchecks the appropriate continent check box.

Categories: Software

Prevent route change in Vue router

Mon, 2017-08-28 03:48
<router-link to="SOME_ROUTE"> <div class="outer-div"> <div class="inner-div" v-on:click="doSomething"></div> </div> </router-link>

Some I am trying to create a link which will have a image in it. I am trying to make the inner div to do something without triggering the route change, how am I be able to achieve this? I have tried the event modified v-on:click.stop, but it doesn't seem to work, the route will still change after the .inner-div is clicked. Thanks in advance for your kind help.

Categories: Software

Vuex getter not updating value after an array update

Mon, 2017-08-28 02:48

I'm trying to explore vuex, so what I'm trying to do is to get the count or an array when I remove or add values to it. Below are my codes.

home.vue template

<template> <div :class="page.class" :id="page.id"> <h3>{{ content }}</h3> <hr> <p>Registered users count {{ unRegisteredUserCount }}</p> <ul class="list-unstyled" v-if="getUnRegisteredUsers"> <li v-for="(unregistereduser, n) in getUnRegisteredUsers" @click="register(unregistereduser)"> {{ n + 1 }} - {{ unregistereduser.id }} {{ unregistereduser.fname }} {{ unregistereduser.lname }} </li> </ul> <hr> <p>Registered users count {{ registeredUserCount }}</p> <ul class="list-unstyled"> <li v-for="(registereduser, n) in getRegisteredUsers" @click="unregister(registereduser)"> {{ n + 1 }} - {{ registereduser.id }} {{ registereduser.fname }} {{ registereduser.lname }} </li> </ul> </div> </template> <script> export default { name: 'home', data () { return { page: { class: 'home', id: 'home' }, content: 'This is home page' } }, computed: { getUnRegisteredUsers() { if( this.$store.getters.getCountUnregisteredUsers ) { return this.$store.getters.getAllUnRegisteredUsers; } }, getRegisteredUsers() { if( this.$store.getters.getCountRegisteredUsers > 0) { return this.$store.getters.getAllRegisteredUsers; } }, unRegisteredUserCount() { return this.$store.getters.getCountUnregisteredUsers; }, registeredUserCount() { return this.$store.getters.getCountRegisteredUsers; } }, methods: { register(unregistereduser) { this.$store.commit({ type: 'registerUser', userId: unregistereduser.id }); }, unregister(registereduser) { this.$store.commit({ type: 'unRegisterUser', userId: registereduser.id }); } }, mounted: function() { } } </script>

state.js

export default { unRegisteredUsers: [ { id: 1001, fname: 'John', lname: 'Doe', state: 'Los Angeles', registered: false }, { id: 2001, fname: 'Miggs', lname: 'Ollesen', state: 'Oklahoma', registered: false }, { id: 3001, fname: 'Zoe', lname: 'Mcaddo', state: 'New York', registered: false }, { id: 4001, fname: 'Jane', lname: 'Roberts', state: 'Philadelphia', registered: false }, { id: 5001, fname: 'Ellen', lname: 'Jennings', state: 'Houston', registered: false }, { id: 6001, fname: 'Joseph', lname: 'Reed', state: 'Boston', registered: false }, { id: 7001, fname: 'Jake', lname: 'Doe', state: 'Portland', registered: false } ], registeredUsers: [] }

getters.js

export default { getAllUnRegisteredUsers(state) { return state.unRegisteredUsers; }, getAllRegisteredUsers(state) { return state.registeredUsers; }, getCountUnregisteredUsers(state) { return state.unRegisteredUsers.length; }, getCountRegisteredUsers(state) { return state.registeredUsers.length; }, getUserById(state) { } }

mutations.js

export default { registerUser(state, payload) { //find user const user = _.find(state.unRegisteredUsers, { 'id': payload.userId }); // remove user from original array _.remove(state.unRegisteredUsers, { 'id': payload.userId }); // set user object key value user.registered = 'true'; // add user to new array state.registeredUsers.push(user); console.log(state.registeredUsers.length + ' - registered users count'); }, unRegisterUser(state, payload) { //find user const user = _.find(state.registeredUsers, { 'id': payload.userId }); // remove user from original array _.remove(state.registeredUsers, { 'id': payload.userId }); // set user object key value user.registered = 'false'; // add user to new array state.unRegisteredUsers.push(user); console.log(state.unRegisteredUsers.length + ' - unregistered users count'); } }

During page load it renders the array count properly, but when I remove value to the registeredUsers and unRegisteredUsers the count is not updating. What am I missing here? Can anyone explain and what should I do to get the proper count? Thanks

Categories: Software

Full Stack Setup with Python

Mon, 2017-08-28 02:26

In the years past, I've always used Angular 1.x for my front end which was as simple as including a single JS file at the time. Now with the rise of TypeScript in Angular, React, and others, there's now a need for a dedicated NPM build serves which compiles the source into vanilla JavaScript before serving the front-end as an independent project. Please correct me if my understanding of this is in anyway flawed.

At the moment I use Django for all of my backend applications, particularly a REST framework that will enable the frontend to function as a SPA. I've taken a liking to Vue.js as my frontend weapon of choice. My question is (and please forgive me if it seems a bit too broad) how do I setup my project and configure it properly so that I'm not running two servers for both the frontend and backend?

Again, back in the days of Angular 1.x and vanilla JavaScript all I had to do was include a minified angular.js in my static files folder in the backend and the same goes for the standalone version of Vue. Now I'm just so confused what is what and how to properly setting up a full stack project. If you guys, could weigh in, I'd very much appreciate it. Thank you in advance!

npm run dev # running the frontend for Vue.js manage.py runserver # and a Django DRF backend
Categories: Software

Assigning a parent element for each <slot> in Vue

Sun, 2017-08-27 23:22

I have a vue component, say my-component, which is like this:

<div class="outer"> <div class="inner"> <slot></slot> </div> </div>

When I use the component:

<my-component> <p>This is paragraph 1 </p> <p>This is paragraph 2 </p> </my-component>

The produced html becomes this (as it normally should):

<div class="outer"> <div class="inner"> <p>This is paragraph 1 </p> <p>This is paragraph 2 </p> </div> </div>

But instead, I am looking for a way to produce something like this:

<div class="outer"> <div class="inner"> <p>This is paragraph 1 </p> </div> <div class="inner"> <p>This is paragraph 2 </p> </div> </div>

How can I associate one inner div with each of the slot elements?

Categories: Software

Responsive plot grid with measurements | javascript

Sun, 2017-08-27 22:46

I have to make a grid with ruler, that shows measurements between a few points on the grid (how many points and their coordinates on x,y will be given on page load)

So I have to make a functionality that allows to move any of the points to any of the four directions. Been searching for a library for that but did not find any. Something similar is here: http://jsdraw2d.jsfiction.com/demo/curvesbezier.htm

Does anyone of you know anything that would fit my needs? If not, would you recommend simple JS or VueJS to make custom grid for that? Thanks

Categories: Software

Vue - Spotify API Auth. Login problems

Sun, 2017-08-27 22:09

I would like to create an app with Vue SPA (webpack) and the Spotify API. Unfortunately I can't get the Authentication right. So there is a basic code snippet from Spotify Which you can use to build your app. I tried to use that code and rewrite it so I can use it with Vue. That didn't work out quite nice and I have all kinds of problems. I've registered my App, and saved my details such as client id etc.

The original snippet from Spotify

http://jsfiddle.net/JMPerez/62wafrm7/

Problems

  • Code doesn't log the response from the call. The pop up from spotify auth/login gives me a auth token in the url but doesn't close either. Also the display property stays false so it seems there is going something wrong at the login/auth function.

Code:

<button class="button is-spotify" :class="{display : display}" @click="getAuth()">Login to Spotify <i class="fa fa-spotify"></i></button>

Methods

methods: { login(callback) { var CLIENT_ID = '3f6be5c8306741c8ab06713da0a92f59'; var REDIRECT_URI = 'http://localhost:8080/#/account'; function getLoginURL(scopes) { return 'https://accounts.spotify.com/authorize?client_id=' + CLIENT_ID + '&redirect_uri=' + encodeURIComponent(REDIRECT_URI) + '&scope=' + encodeURIComponent(scopes.join(' ')) + '&response_type=token'; } var url = getLoginURL([ 'user-read-email' ]); var width = 450, height = 730, left = (screen.width / 2) - (width / 2), top = (screen.height / 2) - (height / 2); window.addEventListener("message", function(event) { var hash = JSON.parse(event.data); if (hash.type == 'access_token') { callback(hash.access_token); } }, false); var w = window.open(url, 'Spotify', 'menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left); }, getUserData(accessToken) { axios({ method: 'get', url: 'https://api.spotify.com/v1/me', headers: { 'Authorization': 'Bearer ' + accessToken } }) }, getAuth() { this.login(function(accessToken) { this.getUserData(accessToken) .then(function(response) { console.log(response); this.display = true; }); }); } } // end of methods

So when I copy the token from the url, and paste that in as a data property and run the getUserData seperately it does return me the data, like so:

<button class="button is-spotify" :class="{display : display}" @click="getUserData()">Login to Spotify <i class="fa fa-spotify"></i></button>

getUserData function

getUserData() { axios({ method: 'get', url: 'https://api.spotify.com/v1/me', headers: { 'Authorization': 'Bearer ' + this.accessToken } }).then(function(response) { console.log(response); }) }

But that's actually not what I want because than I have to set each hour a new token instead of users who just re authenticate each hour. So, I would like the same result as the basic snippet.

getAuth() { //run login + getUserData //maybe something like: get token and set it to this.accessToken }
Categories: Software

VueJS 2 debounce on multiple components

Sun, 2017-08-27 22:02

I have a Vue component that uses multiple sub-components on it. And on those sub-components I have a watcher that watches for data changes and processes those changes. I would like to implement debounce for this.

watch: { data: { handler: function () { this.processData() }, deep: true } }, methods: { processData: debounce(function () { console.log(this.id) }, 250),

The problem is that debounce works so it executes only on the last sub-component.

I have found a solution for debounce function that accepts an additional id debounceWithId

However there problem is that if I specify this function as follows:

methods: { processData: debounceWithId(function () { console.log(this.id) }, 250, this.id),

the last this.id is undefined.

What would be a correct way of using debounce in multiple components so the function fires separately on each component?

Categories: Software

VueJS 2 input filter groups

Sun, 2017-08-27 20:06

I have an input:

<input type="text" placeholder="filter by country name" />

And a list of lists:

<ul> <li v-for="continent in continents"> {{ continent[0].continent }} <ul> <li v-for="country of continent"> {{ country.name }} ({{ country.callingCodes[0]}}) </li> </ul> </li> </ul>

Which is a list of continents and each one is a list of countries in it. How do I implement search input to show only countries I'm looking for? I tried to display a list of filtered countries but then the app displays them in each continent rather than in just appropriate one.

Categories: Software

Vue reads all the properties of an object when using it (and triggers all the getters)

Sun, 2017-08-27 19:54

I am seeing some unexpected behavior when including an external object as data into a component in VueJs 2.0. Apparently, Vue will automatically read the properties of the object, triggering all their getters, when setting it as data in a component.

See comments in the mounted() function below.

import { web3 } from './web3/web3-load.js' Vue.component('home', { data () { return { web3: null } }, mounted () { console.log(web3) // this dont call any method of the web3 object this.web3 = web3 // this reads the properties of web3 and triggers their getter methods } })

web3 is actually an instance of Web3, and is rather complex, it has several sub-elements and subfunctions.

My question is: Under which condition is it expected the Vue will automatically read all the properties of an object in the back when storing the object inside the framework? And, can this be disabled?

Categories: Software

VueJS display grouped array of objects

Sun, 2017-08-27 17:49

I'm fetching a list of countries from the API and I want to display them in groups by subregion (continent). Like that:

enter image description here

API gives me a response which is an array of objects (countries) and for each object there is a key called 'subregion' - I want to group by that key. I use lodash for grouping, but maybe there is a Vue method I'm not familiar with. My JS code:

var app = new Vue({ el: '#app', data: { countries: null, }, created: function () { this.fetchData(); }, methods: { fetchData: function() { var xhr = new XMLHttpRequest(); var self = this; xhr.open('GET', apiURL); xhr.onload = function() { var countryList = JSON.parse(xhr.responseText); self.countries = _.groupBy(countryList, "subregion"); }; xhr.send(); }, }, });

And HTML:

<li v-for="country in countries"> {{ country.name }} (+{{ country.callingCodes[0] }}) </li>

How can I achieve what's in the picture?

Categories: Software

Vue php laravel - multiple v-if

Sun, 2017-08-27 17:39

I have a problem, because I have to have multifle v-if in my component.

<div v-if="(order.order_products[key].statuses[0].id) != 3 || order.status != 3" >

Can I add a multiple condition in Vue in v-if? This is not working... I tryed also with && but this isn't go too. In documentation is nothing abiut this. Maybe You can help me?

Categories: Software

Vue Element not being rendered

Sun, 2017-08-27 15:36

Hey I am using Vue + Laravel and using webpack.mix for package control.

Currently, stuck on a peculiar issue. I am trying to render component in my app.js file.

App.js

Vue.component('navigation',require ('./views/navigation.vue')); Vue.component('Example', require('./components/Example.vue')); //this works const app = new Vue({ el: '#app', components: { navigation } });

Php Blade File where component is being rendered.

<body> <div id="app"> <div class="container"> <navigation></navigation> </div> </div>

And my navigation component

<template> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data- toggle="collapse" data-target="#navbar" aria-expanded="false" aria- controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Project name</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#contact">Contact</a></li> </ul> </div><!--/.nav-collapse --> </div> </nav>

As the example component comes out of the box so it works, but the navigation component spits out this error.

app.js:814 [Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.

Any help would be appreciated.

Categories: Software

Using VueJs build tools with Laravel

Sun, 2017-08-27 14:07

I am using VueJs with Laravel and am using the Laravel's default installation of VueJs with their Laravel-Mix.

I want to use Babel, Eslint and Vue-Router all of which don't seem to come with Laravel's default installation?

How can I use the Vue Cli to handle all of this with Laravel or do I need to pull everything in separately, something that the Vue Cli was built for?

Categories: Software

vue.js:465 [Vue warn]: Failed to generate render function:

Sun, 2017-08-27 13:44

I got an error like this:

vue.js:465 [Vue warn]: Failed to generate render function: ReferenceError: Invalid left-hand side in assignment in with(this){return _c('div',{attrs:{"id":"test"}},[_c('p',[_v(_s(_f("sum 4")(message)))]),_v(" "),_c('p',[_v(_s(_f("cal 10 20 10")(message)))]),_v(" "),_c('input',{directives:[{name:"model",rawName:"v-model",value:(message | change),expression:"message | change"}],attrs:{"type":"text"},domProps:{"value":(message | change)},on:{"input":function($event){if($event.target.composing)return;message | change=$event.target.value}}})])}

This is my HTML file:

(found in <Root>) <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>vue</title> <script src="D:\library\vue.js"></script> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> </head> <body> <div id="test"> <p>{{ message | sum 4 }}</p> <p>{{ message | cal 10 20 10 }}</p> <input type="text" v-model="message | change"> </div> <script type="text/javascript"> // -----------------------------------------model->view--------------------------------------- Vue.filter("sum", function(value) { return value + 4; }); Vue.filter('cal', function (value, begin, xing) { return value + begin + xing; }); // -----------------------------------------view->model--------------------------------------- Vue.filter("change", { read: function (value) { return value; }, write: function (newVal,oldVal) { console.log("newVal:"+newVal); console.log("oldVal:"+oldVal); return newVal; } }); var myVue = new Vue({ el: "#test", data: { message:12 } }); </script> </body> </html>

I learn vue.js these days,and I found it funny.but this is a big mistake that make me headache......Is there any grammar mistakes?How can I do for this mistake? And what's the meaning of the error? Thank you very much.

Categories: Software

Is there a way we can apply two vue.js libray on one element?

Sun, 2017-08-27 11:36

For example, with vue draggable library we can drag an html element to another position. and with vue selectable libaray, it is possible to allow an element to be selected. But these two props are based on there each two different library.

Is there a way that we can mix in these two vue libraries in the same element, so we can make it draggable and selectable at the same time?

Thank you for your kindness.

Categories: Software

vuejs: router-link params is empty

Sun, 2017-08-27 09:35

I have defined a router-link

<router-link :to="{ path: linkTo + '/' + item.name, params: { id: item.id } }" >{{item.name}}</router-link>

But when I inspect the router-link, the params object is always empty.

enter image description here What i'm doing wrong? If I just output the id with {{item.id}} i get the number...

This is my route

{ path: '/category/:name', component: Category, props: true, name: 'category', meta: { auth: true } },

gregor

Categories: Software

Login in Laravel 5.4 Vue.js app with JWT doesn't work

Sun, 2017-08-27 09:15

It happens that everything works in my laravel/vue.js application excluding the login that I have to implement now.

I'm using JWT and when I try to login from my Vue template it shows this, but when I test the route created on the back end, it returns the Token without any problem, like this.

Here is the code of my login component of the front-end app...

<script> import bar from '../bar.vue' import axios from 'axios'; export default { components: { 'bar': bar, }, data(){ return { email: '', password: '' } }, methods: { login(){ axios.post('http://localhost:8000/api/signin', { email: this.email, password: this.password }, { headers: {'X-Requested-With': 'XMLHttpRequest'} } ) .then( (response) => console.log(response) ) .catch( (error) => console.log(error) ); } } }

Categories: Software

Vue + vuex object mutations

Sun, 2017-08-27 04:25

I have a state:

state: { objects: [ { id: 10, key2: 'smth', key3: 'smth' //etc... }, { id: 12', key2: 'smth', key3: 'smth' //etc... } ] }

I pick one by id and then i want to change the value of keys on picked object.

The problem is vuex tells me that i have to make changes in mutations only. I saw a many solutions like computed: get() set(), or _.deepClone or change only one key. but what i can do to rewrite entire object by id in mutation? My objects in array may be with many keys so write update commit func to every key will be very painful..

Is there a solution to rewrite object with many keys with 1 commit?

And please don't tell me to use lodash or other lbis, only plain vue/js.

Categories: Software

Pages