Vuejs

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

How can I call a statement or method after the loop complete on vue component?

Thu, 2017-07-20 07:22

My vue component like this :

<template> <div class="row"> <div class="col-md-3" v-for="item in items"> ... </div> </div> </template> <script> export default { ... computed: { items() { ... } }, ... } </script>

If the loop complete, I want to call a statement or method

So the statement is executed when the loop completes

How can I do it?

Categories: Software

How do I emit an event after dispatch in VueJS?

Thu, 2017-07-20 06:35

I have a parent component with a grid of rows and I am using vuex to pass data, as i add a new record I would want to open the newly added record in a modal window. I am emitting an event and opening the modal with the first record (index = 0). The problem is that, as it is an ajax call to add record using an vuex "action", the emit happens before the record is added. How can I wait till the record is added with event? or Is there a better way to do it?

Below is the code:

<!-- Grid Component --> <grid> <addrow @newrecordadded="openNewlyAddedRecord"></addrow> <gridrow v-for="row in rows" :key="row._id"></gridrow> </grid> computed: { rows(){ return this.$store.state.rows; } }, methods:{ openNewlyAddedRecord(){ this.openmodal(this.rows[0]) } }

my store.js

state: { rows : [] }

so in addrow component once the user clicks on submit form it dispatches to vuex

methods:{ onsubmit(){ this.$store.dispatch('addrow',this.newrow); this.$emit("newrecordadded"); } }

actions.js

addrow({ commit,state }, payload){ var url = "/add"; Axios.post(url,payload) .then(function(response){ commit('addnewrow',response.data); }); }

mutations.js

addnewrow(state,payload){ state.rows.unshift(payload); }

Or alternatively can we pass a call back function to dispatch?

Categories: Software

Calling cross domain requests from almost static site

Thu, 2017-07-20 05:44

I'm using vuejs and almost everything I do is on client-side, but for thing I need to call the server-side to check if URL exists or not.

I don't want to make these requests from browser, because that doesn't make sense to fetch different website from my scripts that will be more like calling any bad website without user knowing it in background, so I need to call cloud-function(gce) or aws lambda(since I don't want to host the site on server for it, since it has just one api call).

What would be the best way to accomplish it, I'm looking for something like website is www.webapp.com and cloud-function call on www.webapp.com/checkUrl

Categories: Software

Initialize Vue app after Firebase auth state changed

Thu, 2017-07-20 04:53

I have a bit of a conundrum in my Vue/vuex/vue-router + Firebase app. The bootstrap code is supposed to initialize Firebase, as well as the signed in user (if any) in Vuex:

new Vue({ el: '#app', router, store, template: '<App/>', components: { App }, beforeCreate() { firebase.initializeApp(firebaseConfig) // Because the code below is async, the app gets created before user is returned... .auth().onAuthStateChanged(user => { this.$store.commit('syncAuthUser', user) // this executes too late... }) } })

In my routes, I have

{ path: '/home', name: 'Home', component: Home, meta: { requiresAuth: true } }

as well as

router.beforeEach((to, from, next) => { let authUser = store.getters.authUser // this is not set just yet... if (to.matched.some(record => record.meta.requiresAuth)) { if (!authUser) { next('signin') // /home will always hit here... } next() } else { next() } }) Problem

As mentioned in the comments, the app gets the authenticated user too late. So, when you go to /home while logged in, the app will run the beforeEachcheck in the routes... And the user instance will not be available just yet, so it will think that you are not logged in, when in fact you are (it's clear from my computed properties that are properly updated a few moments later).

Question

So, how do I change my code, so that the Vue app gets initialized only after Firebase returns the user and after that user is passed to the Vuex store? Plese let me know if I am doing something completely wrong.

Attempts
  1. I tried the "unsubscribe" approach; however, its problem is that the onAuthStateChanged would only be triggered once. So, if I put my crucial this.$store.commit('syncAuthUser', user) there, then that code would only execute when the app is created, and not when the user logs out for example.
  2. I also tried a better approach here. I did work for me, but I felt bad wrapping onAuthStateChanged in another Promise, for sure there must be a better way; plus, it seems wrong to place the auth user initialization login in the routes file.
Categories: Software

How to use array reduce with condition in JavaScript?

Thu, 2017-07-20 04:51

So I have an array

const records = [ { value: 24, gender: "BOYS" }, { value: 42, gender: "BOYS" }, { value: 85, gender: "GIRLS" }, { value: 12, gender: "GIRLS" }, { value: 10, gender: "BOYS" } ]

And I want to get the sum so I used the JavaScript array reduce function and got it right. Here is my code:

someFunction() { return records.reduce(function(sum, record){ return sum + record.value; }, 0); }

With that code I get the value 173 which is correct. Now what I wanted to do is to get all the sum only to those objects who got a "BOYS" gender.

I tried something like

someFunction() { return records.reduce(function(sum, record){ if(record.gender == 'BOYS') return sum + record.value; }, 0); }

But I get nothing. Am I missing something here? Any help would be much appreciated.

Categories: Software

How do I use flask templating with Vuejs's “Mustache” syntax?

Thu, 2017-07-20 03:44

It seems there is some overlap.

For instance, this code:

<div id="entry"> <textarea rows="20" v-model="input"></textarea> <div> {{ input | md }} </div> </div> <script src="https://unpkg.com/vue@2.1.3/dist/vue.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.6/marked.min.js"></script> <script> var vm = new Vue({ el: '#entry', data: { input: '' }, filters: { md: function(val){ return marked(val) } } }) </script>

seems to work alright here: https://jsfiddle.net/5qvc815w/ (aside from the html tags rendered in the markdown)

but in flask I am getting

jinja2.exceptions.TemplateAssertionError TemplateAssertionError: no filter named 'md'

it seems to be looking to jinja2 to discover whats in the curly braces instead of in vue.js which it should be doing.

Categories: Software

Vuejs Local Directive Not Binding To Data When Passing A Method To Call

Thu, 2017-07-20 03:14

Defining a vuejs directive locally has issues when calling a method when being bound locally.

The problem: on tab/enter, look-up a value and set it based on what comes back (ie; setTimeout is the fake http call). Upon set time out completing, update the compute property.

I am aware of the migration docs says to use an 'eventHub' to communicate between the directive and the parent component. Is there another way to do this? If you check out the fiddle below, the global directive works perfectly while the local directive fails. I feel like the vm is not being bound properly on the local directive.

Local directive:

new Vue({ el: '#vue', directive: { localSomething: { bind (el, b, n, o) { $(el).on('keydown', function(e) { if(e.keyCode == 13 || e.keyCode == 9) { b.value($(el).val()); } }); } } }, ...

Global directive:

Vue.directive('globalSomething', { bind (el, b, n, o) { $(el).on('keydown', function(e) { if(e.keyCode == 13 || e.keyCode == 9) { b.value($(el).val()); } }); } });

Html:

Local: <input v-local-something="doSomething" /> Global: <input v-global-something="doSomething" />

Method:

methods: { doSomething: function(value) { let vm = this; setTimeout(function() { vm.item.name = value; }); }

Fiddle here: https://jsfiddle.net/4g1xyy9h/

Categories: Software

Vuejs Tinymce - It's not working

Thu, 2017-07-20 00:51

Can you show me how can I run TinyMCE from VueJS2

I tried everything

I want to run it with this package https://www.npmjs.com/package/tinymce-vue-2 but i can't find out how to do it

thank you

Categories: Software

Facebook Firebase Auth Error

Thu, 2017-07-20 00:51

I'm building a small app and want to authenticate it via Facebook. I have enabled Facebook as an auth method in the Firebase dashboard, provided my Facebook app tokens and the auth URI to Facebook.

This issue is this:

Uncaught TypeError: WEBPACK_IMPORTED_MODULE_0__firebase_config_js.a.FacebookAuthProvider is not a constructor

Here is the Vue JS Method in question:

const sphinx = firebaseApp.auth()

methods: { signUp (event) { sphinx.getRedirectResult().then(function (result) { if (result.credential) { var token = result.credential.accessToken } var user = result.user console.log(token, user) }) // Start a sign in process for an unauthenticated user. var provider = new sphinx.FacebookAuthProvider() sphinx.signInWithRedirect(provider) } }

It seems to have something to do with the line:

var provider = new sphinx.FacebookAuthProvider()

But I'm still fairly new to JS, but I think the issue is related to new in an ES6 environment? And if so, how can I change this.

Categories: Software

How to pass Laravel data(json) to Vue component

Wed, 2017-07-19 23:50

I want to pass an Laravel object to my Vue component. In Vue I want to parse the data to an JSON object and I already tried this solution.

In my blade I have this:

<creator :object="parseData({{ $object->toJson() }})"></creator>

And in my component I have this:

data() { return { ball: null } }, parseData(data) { this.object= JSON.parse(data); }

This gives me the following error:

[Vue warn]: Property or method "parseData" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

Can you tell me what I am doing wrong?

Categories: Software

How to load others page's resources after login page complete loading

Wed, 2017-07-19 23:47

how to archive it and I use vue-cli to build my project. I have two ideas:1.change webpack config.2.use ''.Had someone archive it?

Categories: Software

VueJS - manipulate DOM after computed

Wed, 2017-07-19 23:36

I'm getting posts and comments from an API, using Vuex. Right now, I have:

mounted () { this.$store.dispatch('getComments', this.post); }, computed: { comments () { return this.$store.getters.orderedComments; },

The comments body is a string that contains HTML tags. I need to strip out the href attribute from a tags of a given class.

cleanUnwantedLinks () { const link = document.getElementsByClassName('link-class')[0]; link.removeAttribute('href'); }

I'm not sure how to call cleanUnwantedLinks. It should be called just after the component is mounted (when I have the comments already). Is there a way to do it?

Categories: Software

Is it possible to Import file in JS file using URL

Wed, 2017-07-19 23:33

I have little older version of vue.js ("vue": "^2.2.2") defined in package.json

Which I access in my JS like this:

import Vue from 'vue'

But, I like to quickly test if things are working fine with newer version of vue.js.

import Vue from '//unpkg.com/vue@2.4.1'

If not possible, any better ways?

Categories: Software

How to handle anchors (bookmarks) with Vue Router?

Wed, 2017-07-19 23:07

I'm looking for a smart way to handle in-page anchors with Vue Router. Consider the following:

<router-link to="#app">Apply Now</router-link> <!-- some HTML markup in between... --> <div id="app">...</div>

The "scroll to anchor" behavior described in the docs works fine except:

  • When you click on the anchor, it brings you down to the div id="app". Now scroll away from the div back to the anchor and try clicking it again -- this time you will not jump down to the div. In fact, the anchor will retain the class router-link-active and the URL will still contain the hash /#app;
  • With the steps above, if you refresh the page (the URL will still contain the hash) and click on the anchor, nothing will happen either.

This is very unfortunate from the UX perspective because a potential customer has to manually scroll all the way down to reach the application section.

I was wondering if Vue Router covers this situation. For reference, here's my router:

export default new VueRouter({ routes, mode: 'history', scrollBehavior(to, from, savedPosition) { if (to.hash) { return { selector: to.hash } } else if (savedPosition) { return savedPosition; } else { return { x: 0, y: 0 } } } })
Categories: Software

Show Apollo mutation error to user in Vue.js?

Wed, 2017-07-19 21:20

I am using Vue.js with Vue-Apollo and initiating a User mutation to sign in a user. I am using the graph.cool service.

I have a request pipeline function setup to catch some errors, like an invalid email.

When the request is made with bad / invalid input, my error catch() fires (as expected) and in the network tab I can see the JSON for the custom errors messages. But how do I access these errors / response from within the catch if an error is triggered from graph.cool?

Example:

signin () { const email = this.email const password = this.password this.$apollo.mutate({ mutation: signinMutation, variables: { email, password } }) .then((data) => { // This never fires on an error, so I can't // show the user the errors in the network repsonse. console.log(data) }) .catch((error) => { // Error in this part fires in the console // but I'm unable to show the JSON response // errors because the 'then()' above doesn't execute. console.error(error) }) }

I get the following error for an unrecognised user:

Error: GraphQL error: No user found with that information at new ApolloError (eval at (app.js:956), :34:28) at eval (eval at (app.js:1353), :139:33) at

Any idea how to show the errors in the response from within the catch()?

I can literally see the errors I want to show to the user in the response on the network tab here:

enter image description here

...but I can't figure out how to do it.

Any help much appreciated! Thank you.

Categories: Software

Aframe a-sky rotation not updating

Wed, 2017-07-19 20:58

I need you help! I have integrated aframe into my Vue js project and I need the rotation data from the a-sky element in this particular situation. As I move the a-sky in the browser, the rotation data does not update, even if I check it in the aframe inspector.

<a-scene embedded> <a-entity camera look-controls="reverseMouseDrag: true" position="0 1 3" ></a-entity> <a-text font="roboto" width="30" align="center" color="#ccc" opacity="1" value="North" position="0 -3 -4"></a-text> <a-text font="roboto" width="30" align="center" color="#ccc" opacity="1" value="South" position="0 -3 10" rotation="0 -180 0"></a-text> <a-text font="roboto" width="30" align="center" color="#ccc" opacity="1" value="East" position="8 -3 3" rotation="0 -90 0"></a-text> <a-text font="roboto" width="30" align="center" color="#ccc" opacity="1" value="West" position="-7 -3 3" rotation="0 -270 0"></a-text> <a-sky id="sky" :src="getPanoImage" rotation="0 -130 0" :phi-start="getPhi"></a-sky>

I have my created() hook set up for listening to changes, but since there is no change, the listener does not fire.

created() { document.querySelector('#sky').addEventListener('componentchanged', function (evt) { if (evt.detail.name === 'rotation') { console.log('Camera rotation went from', evt.detail.oldData, 'to', evt.detail.newData); } });

},

Any suggestions are appreciated.

Categories: Software

v-for causing actions to be applied to all divs

Wed, 2017-07-19 20:27

Previously I asked a question about removing a custom truncate filter in Vue. Please see the question here:

Removing a Vue custom filter on mouseover

However, I neglected to mention that I am using a v-for loop and when I hover over one div, I am noticing that all the divs in the loop are having the same action applied to them. I'm not sure how to target only the div that is being hovered over. Here is my template:

<div id="tiles"> <button class="tile" v-for="(word, index) in shuffled" @click="clickWord(word, index)" :title="word.english"> <div class="pinyin">{{ word.pinyin }}</div> <div class="eng" @mouseover="showAll = true" @mouseout="showAll = false"> <div v-if="showAll">{{ word.english }}</div> <div v-else>{{ word.english | truncate }}</div> </div> </button> </div>

And the data being returned:

data(){ return { currentIndex: 0, roundClear: false, clickedWord: '', matchFirstTry: true, showAll: false, } },

If you know Vue, I would be grateful for advice. Thanks!

Categories: Software

using vue.set in vuex is not updating the state

Wed, 2017-07-19 20:27

im trying to add a object into a nested array, and its not working, but iv used this for other states and it works fine.

Has it got something todo with it begin a nested array?

this is the code im using

Vue.set(state.sections[getCurrentSection(state).index].rows[getCurrentRow(state).index].columns[getCurrentColumn(state).index].elements, 0, element)

this is the element object

var element = { id: id, style: { backgroundColor: { value: 'rgba(255,255,255,1)', }, }, }

what am i doing wrong?

Categories: Software

Need the same functionality as a computed property, but I need to be able to update the data after initial change

Wed, 2017-07-19 19:39

I have a situation where I need to update data when it detects changes to a state. The user needs to be able to make further changes this info within a textarea. Using computed properties pulls in the data exactly how I want, but any changes made by the user after this are overridden because the computed property keeps changing this data back to it's initial values. What would be the best way to pull in data initially upon a state change but then allow for editing after that point?

Thanks!

Categories: Software

Removing a Vue custom filter on mouseover

Wed, 2017-07-19 18:48

I would like to remove a truncate filter on mouseover using VueJS 2. Here is my filter in the template:

<div class="eng" @mouseover="showAll">{{ word.english | truncate }}</div>

And here is the filter itself:

filters: { truncate: function(value) { let length = 50; if (value.length <= length) { return value; } else { return value.substring(0, length) + '...'; } } },

Is there a way to remove the filter on the mouseover event so that the div is not truncated anymore? Thanks!

Categories: Software

Pages