Software

v-for : is there a way to get the key for the nested(second) loop besides "Object.keys(obj)[0]" in Vuejs?

Vuejs - Fri, 2017-09-08 15:08

Here's the markup:

<ul> <li v-for="(topic,label,index) in guides" :key="index"> <ul> <strong> {{label}} </strong> <li v-for="rule in topic"> {{rule.val}}, {{Object.keys(topic)[0]}} </li> </ul> </li>

And here's the data for this list:

data: { guides: { "CSS" : { 1502983185472 : { "modifiedby" : "bkokot", "val" : "When adding new rule, use classes instead of ID whenever possible" }, 1502983192513 : { "modifiedby" : "bkokot", "val" : "Some other rule" }, }, "Other" : { 1502628612513 : { "modifiedby" : "dleon", "val" : "Some test text" }, 1502982934236 : { "modifiedby" : "bkokot", "val" : "Another version of text" }, } } }

So as you can see there is a "guides" property which is an object of other objects that do have inner objects too. All I want is to get the keys from inner (second) loop (numbers "1502983185472" etc). The only solution that i see right now is "Object.keys(topic)[0]", but is there a more accurate alternative in vuejs for this? Adding key, index parameters to the second loop(with new unique variable names) doesn't work for me.

Here's a working fiddle: https://jsfiddle.net/thyla/yeuahvkc/1/

Please share your thoughts. If there is no good solution for this - may it be a nice topic for a feature request in Vuejs repo(unless I'm missing something terrible here)? Generally if you're curious - that number is a momentjs timestamp - I'm using this data in firebase, and saving initial timestamp as an object key seemed to be a pretty nice solution (since we need a key anyway, to save some space - I can use this key instead of another extra timestamp property in my object, this also makes the instance very 'targetable' in firebase).

Thank you in advance ! Cheers!

p.s: another possible solution is converting inner loop (css, other) from objects into arrays and using time-stamp as another object property, but I'm using firebase - saving this data as an object gives me an ability to quickly access some instance without parsing the entire parent object/array, makes it more easy to filter, search, reupdate, etc - thus converting object into array is not a good solution for instance with very large number of items.

Categories: Software

trying to POST JSON object by FormData append

Vuejs - Fri, 2017-09-08 14:50

i'm posting JSONobject by FormData() but in back end result i got Count 0 but that data what i'm sending is empty result is null

Categories: Software

Javascript dont async function [duplicate]

Vuejs - Fri, 2017-09-08 14:39

This question already has an answer here:

How can i do for having coord immediatly :

this.latitude = 0; this.longitude = 0; navigator.geolocation.getCurrentPosition(position => { this.latitude = position.coords.latitude this.longitude = position.coords.longitude console.log('lat : ' + position.coords.latitude) console.log('long : ' + position.coords.longitude) }) console.log(' too late : '.this.latitude) console.log(' too late : '.this.longitude)

Result : too late : 0 too late : 0 lat : 0.123456 long : 40.23456

How can i do for having : lat : 0.123456 long : 40.23456 too late : 0.123456 too late : 40.23456

Thank you !

Categories: Software

Vue.js 2 does not update child when in hidden state

Vuejs - Fri, 2017-09-08 14:39

I have a page which renders a child component (chart) that is passed the data that fills the chart as a prop (list). It is being shown and hidden by a div that wraps it, and my problem is that when it is shown and my data (list) changes, it will properly redraw and update. But if it is hidden while the data changes, and then shown again, NOTHING draws at all in the space, it is blank, not even the previous chart. It looks roughly like this:

<div class="bluecards"> <div v-on:click="isShowpie = !isShowpie"> My clickable bar title that hides/shows Pie below </div> <div v-show="isShowpie" class="content"> <div class="chartwrapper"> <pie-chart v-if="loaded" :list="list" class="pchart"></pie-chart> </div> </div> </div>
Categories: Software

Passing values between exported and non-exported part of script

Vuejs - Fri, 2017-09-08 14:28

How to pass values between exported part of a script and non-exported one?

The construction looks like this:

<script> // PART 1: import { EventBus } from './event-bus.js'; EventBus.$on('value-received', value => { this.receivedValue = value; }); // PART 2: export default { data() { return { receivedValue: '' } }, watch: {...}, methods: {...} } </script>

How can I get the value assigned to receivedValue variable and made usable by Vue methods?

Categories: Software

Wrong focus after closing a 2nd modal

Vuejs - Fri, 2017-09-08 13:49

I'm using vue.js 2 and bootsrap 3 to open a modal that opens a 2nd modal.

Few days ago, I asked a question on how to set a focus on a control contained in a 2nd modal. I got a great answer that solved the issue.

Problem When opening the 1st modal, the user is able to scroll through it to see its bottom. But after opening and closing the 2nd modal, the focus moves to the page that contains the 1st modal. and when the user scrolls to see the rest of the 1st modal, he scrolls the page behind that 1st modal.

It is very uncomfortable to use especially when the modal is bigger than the screen height. Is there a way to prevent this?

To reproduce this issue, open the answer and click on "Expand snippet"

Categories: Software

How to show Vee validate all errors for one field

Vuejs - Fri, 2017-09-08 13:30

I want to see all errors for one field. But it always show me the first one. enter image description here

Categories: Software

How to do a transition with some elements in vue.js?

Vuejs - Fri, 2017-09-08 11:55

I want to do transition on my three elements. My text should change to another and my A elements should fade. How to do it correctly?

<transition name="fade"> <div> {{text}} <div v-if="show"> <a @click="show = !show" href="#"></a> <a @click="show = !show" href="#"></a> </div> </div> </transition>
Categories: Software

Vue.js Multiselect / search one attribute for more

Vuejs - Fri, 2017-09-08 11:36

I’m currently working in Vue.js & Laravel (php framework) and I’m using “multiselect”, I’m trying to use it with objects from my database ( I get them with axios). My multiselect works but this happens :

My currently page And I would like only one “denmark” option but when I choose it it show me all the application related to “denmark”.

I used this example : https://gist.github.com/superlloyd/c1ea010a63dade8f3d14948296ac8646#comments1

Do you have any ideas ? :slight_smile:

Thank you.

Categories: Software

Vue.js - hide list item when one item is clicked

Vuejs - Fri, 2017-09-08 11:30

I'm new in Vue Js and not sure how to do the following task.

I have a list of items and it should work like the following: If one item from the list is clicked, other items in the list should disappear. How should I do this in Vue.js?

Categories: Software

vuejs typescript property router does not exist

Vuejs - Fri, 2017-09-08 11:30

I try to access router in my typescript class component:

import {Vue} from 'vue-property-decorator' import Component from 'nuxt-class-component' import {Getter, Action} from 'vuex-class' @Component export default class Login extends Vue { @Action login username = '' password = '' async submit () { await this.login({username: this.username, password: this.password}) this.$router.push('/results') } }

Unfortunately, I get:

error TS2339: Property '$router' does not exist on type 'Login'.
Categories: Software

vuejs vuex store.replaceState is not a function in action

Vuejs - Fri, 2017-09-08 11:14

I want to load state from localstorage in an action: However I get store.replaceState is not a function.

loadState (store) { let stateJson = localStorage.getItem('vuex') if(stateJson) { let state = JSON.parse(stateJson) store.replaceState(state) } }
Categories: Software

Vue material - I don't see changes

Vuejs - Fri, 2017-09-08 11:10

I am using http://vuematerial.io/#/getting-started in my vue project (webpack, hot reloads, babel and so on).

I've imported this library (via npm) and included it in main.js file hovewer i don't see any changes in my project. The browser doesnt render it.

What am i doing wrong?

main.js:

import Vue from 'vue' import VueMaterial from 'vue-material' import 'vue-material/dist/vue-material' import App from './App.vue' Vue.use(VueMaterial) Vue.material.registerTheme('default', { primary: 'blue', accent: 'red', warn: 'red', background: 'grey' }) /* eslint-disable no-new */ new Vue({ el: 'body' components: { App }, render: h => h(App) })

App.vue:

<template> <div id="app"> <hello></hello> <md-button>Default</md-button> // this doesnt work! </div> </template> <script> export default { components: { 'hello': Hello, 'documents': Documents, 'Home': Home }, data: function () { return { } } } </script>
Categories: Software

Vuejs testing - Ava - Changing propData

Vuejs - Fri, 2017-09-08 11:09

Im trying to change the propData passed into a component to monitor and check the component.

Im expecting the last console log in this code block to be 5 but its still 2.

import Vue from 'vue'; import test from 'ava'; import AnimateNumber from './../src/components/AnimateNumber.vue'; function instance(propsData) { let N = Vue.extend(AnimateNumber); return new N({propsData}); } test('..', t => { let vm2 = new Vue({ data: { a: 2 } }); let vm = instance({number: vm2.a}).$mount(); // vm.displayNumber is just a copy of the number prop passed in. console.log(vm.displayNumber); // 2 // Set to 5 Vue.set(vm2, 'a', 5); console.log(vm2.a); // 5 Vue.nextTick(function () { console.log(vm.displayNumber); // 2 (Expected 5) }); });
Categories: Software

Laravel API - Authentication works just after reloading the page

Vuejs - Fri, 2017-09-08 11:01

I am trying to build a Single Page Application (SPA) using VueJS as a front-end and Laravel as a back-end.
I am using laravel's passport to manage the authentication tokens etc.
The problem: After login I have to reload the page to be successfully authenticated.

Login method

data() { return { email: '', password: '', } }, methods: { login() { var data = { client_id: 2, client_secret: '****************************', grant_type: 'password', username: this.email, password: this.password } // send data this.$http.post('oauth/token', data) .then(response => { // authenticate the user this.$store.dispatch({ type: 'authenticate', token: response.body.access_token, expiration: response.body.expires_in + Date.now() }) // redirect after successful login if (this.$route.query.from) this.$router.push(this.$route.query.from) else this.$router.push('/feed') }) } }

Get the user information from the backend (just works after refreshing the page)

setUser () { // this route throws 'unauthenticated' error // and works only after refreshing the page this.$http.get('api/users/') .then(response => { this.$store.dispatch({ type: 'setUser', id: response.body.id, email: response.body.email, name: response.body.name }) }) } }

Vuex store

export default new Vuex.Store({ state: { isAuth: !!localStorage.getItem('token'), user: { id: localStorage.getItem('id'), email: localStorage.getItem('email'), name: localStorage.getItem('name') } }, getters: { isLoggedIn(state) { return state.isAuth }, getUser(state) { return state.user } }, mutations: { authenticate(state, { token, expiration }) { localStorage.setItem('token', token) localStorage.setItem('expiration', expiration) state.isAuth = true }, setUser(state, { id, email, name }) { localStorage.setItem('id', id) localStorage.setItem('email', email) localStorage.setItem('name', name) state.user.id = id state.user.email = email state.user.name = name } }, actions: { authenticate: ({ commit }, { token, expiration }) => commit('authenticate', { token, expiration }), setUser: ({ commit }, { id, email, name }) => commit('setUser', { id, email, name }) } })

Laravel route

Route::group(['middleware' => 'auth:api'], function() { Route::get('/users', 'UsersController@users'); });

Laravel function

public function users(Request $request) { return $request->user(); }

The error message

enter image description here
When I reload the page the error message disappears and I am successfully authenticated. I would be very happy for any kind of help!

Categories: Software

vuejs middleware first page load

Vuejs - Fri, 2017-09-08 10:57

I want to redirect the user if he is not logged in via middleware (The current user is first loaded from localstorage)

auth.js

export default async function ({ store, redirect }) { if(!store.state.stateLoaded) { await store.dispatch('loadState') } if (!store.state.user) { redirect('login') } } }

This works fine when I navigate between routes, but not when I initially load the page.

Categories: Software

Vue js Filters in List Rendering: Best Practices

Vuejs - Fri, 2017-09-08 10:23

I'm studying VueJs and as programming allows multiple ways to get to the same result (some more or less elegant)...I'm pondering on what is the best way to filter lists.

Here are a few ways i've noticed lists could be filtered:

I will refer to this new Vue instance:

new Vue({ el: '#app', data() { return { selected:['diesel','petrol'], cars: [ { "color": "blue", "type": "diesel", }, { "color": "red", "type": "petrol", }, { "color": "blue", "type": "diesel", }, ] } }

Method #1: the "v-show". Where any car type pushed into the "selected" array will be rendered.

<div id="app> <span v-for="(car, key) in cars" v-show="selected.includes(car.type)" > {{car.color}} <br> {{joke.type}} <br> </span> </div>

Method #2: Using a computered Property and a filter

<div id="app> <span v-for="(car, key) in filteredCars"> {{car.color}} <br> {{joke.type}} <br> </span> </div> computed: { filteredCars: function(){ var selected = this.selected return this.cars.filter(function(car){ if (selected.indexOf(car.type) >= 0) { return joke.type } } )} }

Any thoughts and best practices??

Thanks again.

Categories: Software

Change variable in component using vue.js

Vuejs - Fri, 2017-09-08 10:22

I have navbar blade, component with text and another components with page. It works like I have component with text in navbar, and another component after navbar. That's three another components. How to change text from for example index.vue in text.vue?

That's what I have:

Text.vue:

<template> <p class="title">{{msg}}</p> </template> <script> export default { props: [ 'msg', ], } </script>

Component in navbar.blade.php:

<title></title>

And I try to change it in index.vue, that should work when we are on this page:

data() { return { msg: 'text', }

But it doesn't work. How to do it correctly?

Categories: Software

Why v-model attribute work differently

Vuejs - Fri, 2017-09-08 09:46

Two equal examples (according to Vue.js) work differently:

First

<input v-model="value" @input.once="setDirty" type="text" id="object-email">

Second:

<input v-bind:value="value" v-on:input="value = $event.target.value" @input.once="setDirty" type="text" id="object-email">

In the first example value changes only after second input, while the second example works correctly. If we delete @input.once attribute, two examples will work fine.

P.S. Vue 2.4.0

Categories: Software

How does this import statement work?

Vuejs - Fri, 2017-09-08 07:24

I just downloaded a template from a vue cli as
vue init webpack my-project.
and inside Hello.vue I saw an import statement like this.
import Hello from '@/components/Hello';

and I am curious what does that @ does. It's used at a lot of places but no where it's written what exactly it does. Would be great if someone can explain what it does?

Categories: Software

Pages