Vuejs

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

Vue JS unable to display to DOM the returned data of method

Wed, 2017-08-02 05:33

Template html

<div class="item" v-for="n, index in teamRoster"> <span> {{ getFantasyScore(n.personId) }} </span> </div>

Method

getFantasyScore(playerId) { if(playerId) { axios.get(config.NBLAPI + config.API.PLAYERFANTASYSCORE + playerId) .then( (response) => { if( response.status == 200 ) { console.log(response.data.total) return response.data.total; } }); } }

I'm trying to display the returned data to DOM but it doesnt display anything. But when I try to console log the data is displays. How can I be able to display it. What am I missing?

Categories: Software

Manully add csrf token With Slim ,Axios and ForData

Wed, 2017-08-02 04:25

I have a a modal that would submit a file without using an actual form, I am using FormData, so upload it to server. This will work if csrf token is disabled, my question is, how would I send the csrf token manually? I am using slim,axios and vuejs.

var formData = new FormData(); formData.append('fileme',file); axios.post(uyab.uploadUrl, formData,{ headers: { 'Content-Type': 'multipart/form-data', 'csrf_name': uyab.csrf_name, 'csrf_value': uyab.csrf_value, 'Accept': 'application/json', }, })

But this will return error of failed csrf token

I created a function that would fetch csrf name and values from specific routes, and thus returning with correct values, the only problem is I dont know how to make it work in vuejs using spa approach

Categories: Software

how to load a component dynamically in vue

Wed, 2017-08-02 03:44
<template> <div> <v-container fluid id="main"> <v-card class="white lighten-4 elevation-3"> <li v-for="stop in stop_name_arr"> {{stop}} </li> <direct_bus_travel_time_in_between_stops> </direct_bus_travel_time_in_between_stops> <direct_bus_travel_distance_in_between_stops> </direct_bus_travel_distance_in_between_stops> </v-card> </v-container> </div> </template>

i have two components direct_bus_travel_time_in_between_stops & direct_bus_travel_distance_in_between_stops to be loaded after <li v-for="stop in stop_name_arr">{{stop}}</li> has been executed completely .

Is there any way to append the components dynamically inside a function to load it when I want it to load ?

Categories: Software

Accessing the DOM in the Vue Mounted function

Wed, 2017-08-02 02:32

How do I access an element from within the mounted function in a VueJS instance.

When I try the following, it tells me that the element is undefined. When I see the DOM it is there. Could this be a case where the element is not rendered before I try to reference it?

document.getElementsByName('transferDate_submit')[0].addEventListener("change",function(){});
Categories: Software

vuejs nuxtjs Error render client side dynamic component

Tue, 2017-08-01 23:49

component image

On server-side this good worked. But in browser - I have message error

error image

Pls help me

Thank you!

Categories: Software

[Vue warn]: Unknown custom element: <testimonial-photo-inner>

Tue, 2017-08-01 22:59

I have just installed VueJS on my website and I'm getting tonnes of console errors like the one above. I am not trying to create any Vue components (yet) but my website does contain a number of custom HTML tags.

Does Vue treat any custom HTML tage (e.g. not one in the HTML spec) as something it needs to compile and will it always complain about tags it doesn't recognise?

Is it possible to switch theses warning off?

Please note: This is not a duplicate of Vue js unknown custom element

The user there is actually trying to create a Vue component.

Categories: Software

Cannot access 'this' in TypeScript Vue Component constructor

Tue, 2017-08-01 22:33

I had been doing something like this for a long time:

@Component({ template, name: 'Something' }) export class Something extends Vue { someParam: string; constructor() { super(); this.someParam = this.$route.params.someParam; } }

I'm not which one affected the change, but since upgrading to:

"vue": "~2.4.2", "vue-router": "~2.7.0", "typescript": "~2.4.2",

Now I get this error:

[Vue warn]: Error in data(): "TypeError: Cannot read property '_route' of undefined" vue.esm.js:566 TypeError: Cannot read property '_route' of undefined

None of my code changed, so what changed in Vue or TypeScript (or anything else), why did this stop working, and how can I fix it?

I started moving these to beforeCreate() but they are all over the application, so it's a significant change if I can't find a fix that doesn't require a major refactor.

Thanks

Categories: Software

vuejs get data on <input type="hidden"

Tue, 2017-08-01 22:30

When I try get data "Id" of my list the script get Id wrong.

I need Id that field. but my return is wrong

I stay use a hidden because I not how get that id without use hidden imput

</tr> <tr v-for="todo in todos"> <td>{{todo.filial}} Id {{todo.Id}}<input type="hidden" name="Id" id="Id" v-mode="todo.Id"></td> Deletar: function (event){ alert($('#Id').val()); /*$.post( "Salva.php", { textoDoFormulario: this.todosView.Id, status: "delete" } ); $.get('t2576.php', function(resp) { todosView.todos = resp; }, "json");*/ },
Categories: Software

Laravel 5.4 isn't sending an event to the window

Tue, 2017-08-01 21:59

I tried to integrate flash messaging using the session variable. The problem is that when I integrated Vue, the window stopped receiving the event.

From the controller:

return redirect('home') ->with('flash', 'Signed');

And on my app.js:

window.Vue = require('vue'); window.events = new Vue(); window.flash = function (message) { window.events.$emit('flash', message); };

I think the important part of the Vue component is this line here:

created() { window.events.$on( 'flash', (message) => this.flash(message) ); }

If I type flash('message') in the console, I will see a flash message pop up and it will appear as an event in the Vue Dev Tools.

But for some reason it's not getting it from the controller. Any ideas?

Categories: Software

VueJS - Rest call in unit test

Tue, 2017-08-01 21:49

I'm making a rest call and saving the response to expectedServices, however it doesn't seem to be ready when I test it (says its undefined).

it(`should get the serviceList from /services endpoint`, done => { // Extend the component to get the constructor, which we can then initialize directly. const Constructor = Vue.extend(Products); const comp = new Constructor().$mount(); var expectedServices; axios.get('http://localhost:9090/services') .then((resp) => { expectedServices = resp.data; }) .catch((err) => { expectedServices = resp.data; }) Vue.nextTick(() => { expect(JSON.stringify(comp.serviceList)).to.equal(JSON.stringify(expectedServices)); done(); }); });
Categories: Software

FeathersJS and VueJS 2 coexistence (repo)

Tue, 2017-08-01 21:20

I want a simple way to have scaffolded versions of feathers and vue, where they both use their -cli utilities, but in such way they don't mess with each other, but can be deployed at once. Requisites:

  1. I don't feathers-js to recompile things because something changed in the vue sub-folder.
  2. I want to deploy everything to heroku and build as it is just one thing (that is, only one "package.json", only one "npm start".
  3. I want to use express capabilities of feathers to not only provide the rest/sockets services but also, serve the html/vue-bundled-js.

I've seen several examples where you just create one "server" and one "client" folder, which is great for separation between client-server, but then... how do you include the vue app bundle into the feathers served static (public) and to make all happen seamlessly.

Also please let me know if I'm wrong with any of my "requirements" (a.k.a.: I should change my mindset).

Categories: Software

How to seperate Vue logic in a laravel app based on layout and page templates

Tue, 2017-08-01 21:13

I have a laravel app and a Vue instance attached to the body (or a div, just inside the body).

const app = new Vue({ el: '#app' });

I think it makes sense to use the Vue instance for stuff relating to the layout (eg header, nav, footer logic).

Now I have a form that is visible on a specific route (e.g. example.com/thing/create). I want to add some logic to it, e.g. hiding a field based on selected option in the form. It is logic meant for just this form (not to be reused). I prefer not to put all the logic inline with the form but put it in the app.js. I could put it in the Vue instance bound to the body but that sounds odd as it only applies to the form that is much deeper into the dom.

I want to leave the markup of the form in the blade template (that inherits the layout).

I tried creating a component but am not sure how to bind this inside the main Vue instance. What is the best way to handle things for this form, put it in the app.js and have it somewhat structured, putting the variables somewhat into scope. Or is it really necessary to remove the main Vue instance bound to the full layout code?

What I tried was something like this, but it does not work (attaching it to the <form id="object-form"> seems to fail:

var ObjectForm = { template: function() { return '#object-form'}, data: function() { return { selectedOption: 1 } }, computed: { displayField: function() { // return true or false depending on form state return true; } } };

Things do work if I remove the #app Vue instance or when I put everything directly in the app Vue instance. But that seems messy, if I have similar variables for another form they should be seperated somewhat. I would appreciate some advice regarding the structure (differentiate page layout and page specific forms) and if possible some example to put the form logic inside the main app.js.

Categories: Software

Testing API call in Vue with Moxios

Tue, 2017-08-01 20:10

I am having trouble figuring out how to test an API call that happens in the "mounted" lifecycle hook.

I have a single file component that is responsible for displaying some information about an "Owner".

This works exactly how I want / expect in the browser.

<template> <div> <h3>Owner Information</h3> <table class="table table-striped table-condensed"> <thead> <th>Name</th> <th>Address</th> <th>Social Security Number</th> <th>Ownership Percentage</th> </thead> <tbody> <tr :data-owner-id="owner.id" v-for="owner in owners"> <td>{{ owner.name }}</td> <td>{{ owner.address }}</td> <td>{{ owner.censored_ssn }}</td> <td>{{ owner.ownership_percentage }}</td> </tr> </tbody> </table> </div> </template> <script> import axios from 'axios'; export default { data() { return { principal_id: '', owners: [] } }, mounted() { const el = document.querySelector('#owner-information'); this.principal_id = el.dataset.principal; var self = this; axios.get(`/principals/${this.principal_id}.json`).then(response => { response.data.owners.map((owner) => { owner.score = ''; owner.link = ''; owner.last_pull_date = ''; self.owners.push(owner); }); }); .catch(e => { console.log(e); }); } } </script>

For testing, I am using Karma, Jasmine, and Avoriaz.

Here is a failing test:

import { mount } from 'avoriaz' import OwnerInformation from '../../app/javascript/packs/OwnerInformation.vue' describe('OwnerInformation', () => { let component beforeAll(() => { const element = document.createElement('div') element.setAttribute('id', 'owner-information') element.setAttribute('data-principal', '84033') document.body.appendChild(element) component = mount(OwnerInformation) component.vm.$mount('#owner-information') }) it('retrieves owner information from the API', () => { expect(component.data().owners.length).toBe(1) }) })

The above expects 1, but gets 0.

So now I figure that I need to stub/mock out my API request in some manner. A quick Google search leads me to moxios. So I install it with Yarn and eventually come up with this. I am not 100% sure where to put moxios.stubRequest, but have tried putting it in beforeAll(), beforeEach(), and inside the "it".

```

import moxios from moxios import { mount } from 'avoriaz' import OwnerInformation from '../../app/javascript/packs/OwnerInformation.vue' describe('OwnerInformation', () => { let component beforeAll(() => { const element = document.createElement('div') element.setAttribute('id', 'owner-information') element.setAttribute('data-principal', '12345') document.body.appendChild(element) component = mount(OwnerInformation) component.vm.$mount('#owner-information') }) beforeEach(() => { moxios.install() }) afterEach(() => { moxios.uninstall() }) it('retrieves owner information from the API', () => { moxios.stubRequest('/principals/12345', { status: 200, response: { id: 1, owners: [ { name: 'Test Owner', address: '123 Test St.', ssn: '123-12-1234', ownership_percentage: 100 } ] } }) expect(component.data().owners.length).toBe(1) })

It appears that the request is not actually be stubbed out. To troubleshoot, I put a console.log statement just before the axios.get() call (which logs out successfully) and I also put a console.log to log out the response, but this one never shows up which makes me think that the axios request is not working and is not getting "intercepted" by moxios.

... console.log('CALLING API...') axios.get(`/principals/${this.principal_id}.json`).then(response => { console.log('***********************') ...

When I run the test I do see a 404, but am unsure why:

01 08 2017 12:49:43.483:WARN [web-server]: 404: /principals/12345.json

To me, it makes most sense to stub out the request at the top of beforeAll(), but this does not work either.

How can I arrange this so that moxios stubs out the API request and it returns so that my test passes?

Categories: Software

Handling form submission without replacing template in VueJS

Tue, 2017-08-01 19:29

First of all, please be kind. I'm new to VueJS coming from the Angular world where things are different ;-)

I am creating a multi-page website using VueJS for simple things like a floaty header and submission of forms etc. I'd like the markup for my contact form to be in my HTML (rendered by the CMS) and I'd like to have VueJS handle the form submission and replacing the form with a thank-you message. So, a simplified version of the form would look like this.

<contact-form> <form class="contact-form_form"> ... <input name="emailaddress" type="text" /> ... <button></button> </form> <div class="contact-form_thanks"> Thanks for filling in this lovely form </div> </contact-form>

So, the obvious thing to do is to create a VueJS component, but I don't want it to introduce a new template, I just want it to submit the form when the button is pressed (using Axios) and hide the form and show the thank you message.

I know how to do all of this in angular using attribute directives and ng-show/hide etc. but can't really see how to do this in VueJS because all the tutorials are geared to wards SPAs and Single file components with templates.

Any kick in the right direction would be appreciated.

Categories: Software

Can't understand this Vuex error coming from Axios request

Tue, 2017-08-01 19:02

I'm using axios to post two requests to update a user profile in my app:

methods: { updateProfileInfo () { let token = this.getAuthToken return axios.patch(`/api/profiles/${this.userid}/`, { bio: this.bio, dob: this.dob, media_url: this.media_url }, { headers: { 'Authorization': 'Token ' + token } }) }, updateUserInfo () { let token = this.getAuthToken return axios.patch(`/rest-auth/user/`, { username: this.username, first_name: this.firstname, last_name: this.lastname }, { headers: { 'Authorization': 'Token ' + token } }) }, updateProfile () { axios.all([this.updateProfileInfo(), this.updateUserInfo()]) .then(axios.spread(function (resProfile, resUser) { this.$store.commit('SET_USERNAME', this.username) console.log('spread...') console.log(resProfile) console.log(resUser) })).catch(err => { console.log(err) }) }

This is generating the following error (trying to commit username inside updateProfile):

TypeError: Cannot read property '$store' of null at eval (Profile.vue?bbca:206) at wrap (spread.js?3c41:25) at <anonymous>

Here are my mutations in the Vuex store:

mutations: { SET_TOKEN_AUTH(state, key) { state.token = key }, SET_USERID(state, id) { state.userid = id }, SET_USERNAME(state, username) { state.username = username }, USER_LOGOUT(state) { state.token = null state.userid = null state.username = null } },
Categories: Software

vuejs - dynamic input 'types'

Tue, 2017-08-01 18:07

I would like to be able to dynamically change the type of an input field between text and password. I tried doing the following:

<input :type="dynamicInputType"> data() { return { dynamicInputType: 'password' } }

But apparently this doesn't work; vuejs displays the error: v-model does not support dynamic input types. Use v-if branches instead.

It's not clear to me how I can fix this with v-if.

Categories: Software

Vue.js Async component - file promise rejected

Tue, 2017-08-01 18:02

I am trying to solve a strange error. After several hours, I have no idea what is wrong.

I create a component in the template that is supposed to be async:

<div id="app"> <component :is="componentType"></component> </div>

module.js:

Vue.component('login-form', function (resolve, reject) { require(['./login-form'], resolve) });

This works well on all pages except when I want to show a password reset page.

The link where the component loading fails is: test.localhost/password-reset/token?email=email@email.com

This is what I see in the Chrome console:

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}__proto__: Promise[[PromiseStatus]]: "rejected"[[PromiseValue]]: Error: Loading chunk 0 failed. at HTMLScriptElement.onScriptComplete (http://test.localhost/js/manifest.js:104:24)

Any ideas what might be wrong? The same thing works everywhere except this one page. Thanks!

Categories: Software

How to edit tweet styling using node package vue-tweet-embed in vuejs?

Tue, 2017-08-01 16:57

How to use node package vue-tweet-embed in vuejs2?

This is building off the question above. I have code that works to generate the tweets I want but I can't get it to style how I want (especially on mobile, its too small). I've tried a few different styling things but none of them edit the tweet. Literally nothing in the .tweet{} styling or the commented code after changed anything. I would like it to fill the width of the phone increase text size on mobile. Help? Thanks!

<template> <div> <component-view :id="'891397134662193152'" class="tweet"></component-view> </div> </template> <script> export default { name: 'email', components: { 'component-view': Tweet }, } </script> <style scoped> .tweet { font-size: 30px; background-size: 600px; width:100%; margin:0 auto; max-width: 1000px; } /*.tweet a { font-size: 70px; font-weight: normal; line-height: 20px; }*/ /*.tweet p.Tweet-text.e-entry-title { width:100% !important; }*/ </style>
Categories: Software

Vue.js changes data values by itself

Tue, 2017-08-01 16:47

This might sound really strange, but it seems Vue decided to change data values by itself. I have a component :is="currentView" tag. I initially set the currentView data to loading and then change it to authenticate later if a condition is met. This works fine. But when a use has authenticated and I change currentView to loading while authenticating the user, it loads for 0.1 seconds and then shows the authenticate component and does that once more, then it shows the component that it should after authenticating. If I log currentView after setting it to loading it logs authenticate and then loading with around 100 milliseconds in between. I can guarantee that I never set currentView to authenticate by myself.

Any ideas?

Categories: Software

Vue.js components + Laravel right management

Tue, 2017-08-01 16:30

I'm unsure how to procede with using Vue single file components alongside Laravel's right management plugins. In general I'm loading the components on different pages, however different actions in components require different rights available, and passing the available rights directly to component seems kind of unsafe. What would be the correct approach here?

Categories: Software

Pages