Vuejs

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

vuejs include javascript library in spa

Wed, 2017-08-23 04:19

i'am creating spa application using vuejs and i find out that i have 3 option in loading my javascript library like bootstrap.js or jquery.js and other javascript library:

1. first is by include all javascript library that i will use in my application in index.html where my vuejs application will live but i find that there is some javascript library that not working to well

ex: there is some javascript library that calculate page height by selecting some div with specific id="page-container", but that div not loaded when page is rendered from server, so at that moment the javascript will throw error since id="page-container" not exist yet.

2. second is by adding it like this to all my javascript library js

// before you use your files in some components,you should package them // your local files export default { //export your file your_function(){ // defined your function ... } } // now your can use it // your component file <script> import local_file from 'your_file_relative_path' //now you can use it in the hook function created(){ //or other hook function local_file.your_function() //call your function } </script>

but that mean i need to change every javascript library that i use...

3. third is by adding it using npm, and just in the vue component import it, it works okay and feels more natural but not all my javascript library are in npm, some of them is admin template related that i bought from themeforest and will never be in npm.

so which one is a better way or maybe there is much more better way that those 3 option that i find out? its hard to find any tutorial or discussion that mention adding other javascript library to spa vuejs most of them just put a bootstrap into index.html and done.

Categories: Software

Vue js component does not work when VeeValidate is declared

Wed, 2017-08-23 00:51

My problem is that I use a Vue js plugin to generate forms dynamically: https://github.com/icebob/vue-form-generator, and when I use VeeValidate the plugin stops working with no errors. However, the moment I remove Vue.use(VeeValidate) , it works fine. So what could be causing the problem? Here is my code:

import VeeValidate from 'vee-validate'; import VueFormGenerator from "vue-form-generator"; Vue.use(VeeValidate, { errorBagName: 'vErrors' }); Vue.use(VueFormGenerator); new Vue({ el: '#action-button-settings', data: { model: { id: 1, name: "John Doe", }, schema: { fields: [{ type: "input", inputType: "text", label: "ID (disabled text field)", model: "id", readonly: true, disabled: true },{ type: "input", inputType: "text", label: "Name", model: "name", placeholder: "Your name", featured: true, required: true }] }, formOptions: { validateAfterLoad: true, validateAfterChanged: true }, }, methods:{ init() { console.log('hi'); }, } });

HTML:

<template> <vue-form-generator :schema="schema" :model="model" :options="formOptions"></vue-form-generator> </template>

Also, as you can see I rewrote VeeValidator computed property errors to vErrors because it was causing a conflict between the two libraries. Please help.

Categories: Software

Send email after purchase without CMS

Wed, 2017-08-23 00:12

I'm creating a website using Bootstrap and VueJS. I need to implement a payment platform where an email is sent to the customer when he buys a product. Which is the best method to do that ? I saw that mailchimp is a good alternative, but I'm not using a CMS. Any idea ?

Categories: Software

How do i bind select box with input in vuejs?

Tue, 2017-08-22 23:41

I try to bind select box with input so like this I have a select box with some option when selected that information will go to input and when some one put information in the input it should bind in select.Can't figure it out.

<div class="col-md-2 text-center"> <select class="form-control" v-model="selected"> <option v-for="item in inventory" :value="item" :key="item.id"> @{{ item.name }} </option> </select> <p> @{{ selected.id}} </p> </div> <input v-model="inputBind" placeholder="," type="text" class="form-control">

and

new Vue({ el:'#app', data:{ inputBind:'', inventory: [ {name: 'MacBook Air', id: 1}, {name: 'MacBook Pro', id: 2}, {name: 'Lenovo W530', id: 3}, {name: 'Acer Aspire One', id: 4} ], selected: 2 }, created: function() { this.selected = this.inventory.find(i => i.id === this.selected); },
Categories: Software

Is the way I'm writing my Vue components correct?

Tue, 2017-08-22 23:08

Here's the way I am currently writing my Vue components. E.g.

<template> <NavBar></NavBar> <div class="Footer"> <div class="left"> <p>I'm a cool footer on the Left!</p> </div> <div class="middle"> </div> <div class="right"> <p>I'm a cool footer on the Right!</p> </div> </div> </template> <script> import NavBar from './NavBar.vue'; export default { name: 'Footer', components: { NavBar } data () { return { } }, methods: { } }

My question is should I be writing my components like this instead? And if so, what is the difference?

Vue.component('my-component', { template: '<div>A custom component!</div>' }) new Vue({ el: '#example' })
Categories: Software

Delete a record from Ag-grid using rendered button in Vue file

Tue, 2017-08-22 22:49

I'm using an ag-grid to populate list records(rows) in a table. I'm trying to delete a record from the grid-table when the user clicks a "Delete" button in one of the cell. I'm able to add the "Delete" button to the grid but how can I capture the index of the clicked "Delete" in the table and remove that row.

table's grid options are defined in file specials.Vue

*function setGridOptions() { this.gridOptions = { columnDefs: [{ headerName: 'Model', field: 'scModel', editable: params => this.isCellEditable(params), newValueHandler: this.NewValueHandler, width: 120, }, { headerName: 'Delete ', width:50, field: 'delete', cellRenderer: deleteRecordCellRender, }, ], rowData: this.getInitialRowData(), headerHeight: 36, rowHeight: 28, suppressMovableColumns: true, suppressMenuMainPanel: true, suppressMenuFilterPanel: true, suppressMenuColumnPanel: true, suppressContextMenu: true, singleClickEdit: true, rowSelection: 'single', }; }*

The 'Delete' column rendered from 'deleteRecordCellRender' defined in javascript file ag-gridFunction.js

*export function deleteSpecialRecordCellRender() {} deleteSpecialRecordCellRender.prototype.init = deleteSpecialRecordCellRenderInit; deleteSpecialRecordCellRender.prototype.getGui = deleteSpecialRecordCellRenderGetGui; function deleteSpecialRecordCellRenderGetGui() { return this.eGui; } function deleteSpecialRecordCellRenderInit() { console.log('deleteSpecialRecordCellRenderInit this: ', this); this.eGui = `<button class="btn btn-default btn-sm delete-row-button" rel="">Delete</a>`; }*

delete-row-button function defined in specials.Vue file is

$('.delete-row-button').on('click', () => { console.log('made it'); console.log('scope: ', this); console.log('clicked row',$scope.gridOptions.api.getSelectedRows()) });

But It's not getting the selectedRow due to a scope issue. How do I get the selected row index and delete after ?

Categories: Software

Vuejs Component Route Dynamic Selection

Tue, 2017-08-22 22:28

I've got a Vue instance:

new Vue({ el: '#Application', router: Router, components: { 'ExampleDepartment', Application }, data: function() { return { } } });

Inside of my application file, I import the template, sidebar action. Inside the template, I have the following:

<v-list-tile v-for="action in actions" :key="action.label" v-if="action.visibility == true"> ... </v-list-tile>

Then inside, I have the following:

export default { watch: { $route: function() { this.getOrSetPageVisibility(); } }, methods: { getOrSetPageVisibility() { for(let index = 0; index < this.actions.length; index++) { if(this.actions[index].page == this.$router.currentRoute.name) { this.actions.$set(index, { visibility }, true); } } } }, data: function() { return { actions: [ { label: 'Add Sample', icon: 'add_circle', page: 'Sample', visibility: false } ] } } }

So the issue, is every time the page switches I want to load a variation of menu items to the sidebar, but it won't let me modify the array. It complains that $set isn't valid or undefined, and it won't update the component on the change.

I can see that on the menu changes it executes my method through the watch, but fails when modifying the array.

How can I dynamically add to the menu based on selected page?

Categories: Software

How to handle bootstrap tooltip in vueJS?

Tue, 2017-08-22 21:12

everyone)

I build a Russian-Chinese language economical game.

I want to do a tooltip over the image. My app is written on vue.js, so I am going to put bootstrap code into vueJS.

In my idea in the tooltip it should be written the description of the economic term (src_russian) or the Russian name of this term (src_chinese). But in reality, tooltip tells me "gameprop.name" and "gameprop.description" only.

Here is my code:

HTML:

<div id="game"> <ol> <game-card v-for="card in cardList" v-bind:gameprop="card" v-bind:key="card.id"> </game-card> </ol> </div>

JS:

Vue.component('game-card', { props: ['gameprop'], template: '<span><a href="#" data-toggle="tooltip" title="gameprop.name"><img :src = "gameprop.src_chinese" /></a><a href="#" data-toggle="tooltip" title="gameprop.description"><img :src = "gameprop.src_russian" /></a></span>' }) var game = new Vue({ el: '#game', data: { cardList: [ { id: 0, src_chinese: 'img/actions/actions_chinese.jpg', src_russian: 'img/actions/actions_russian.jpg', name: "Акция", description: "Акция – ценная бумага, свидетельствующая о внесении средств в капитал акционерного общества и дающая право на получение части прибыли в виде дивидендов" }, { id: 17, src_chinese: 'img/vexel/vexel_chinese.jpg', src_russian: 'img/vexel/vexel_russian.jpg', name: "Вексель", description: "Вексель — ценная бумага, оформленная по строго установленной форме, удостоверяющая перетекание одного обязательства в другое обязательство и дающая право лицу, которому вексель передан на основании соответствующего договора, на получение от должника определённой в векселе суммы" }, ] } }) Vue.directive('tooltip', function(el, binding){ $(el).tooltip({ title: binding.value, placement: binding.arg, trigger: 'hover' })

Where is my mistake?

Categories: Software

VueJS Toggle class to specific element in table

Tue, 2017-08-22 20:47

I can’t seem to figure out how to toggle a class on a specific item in a table. I’m using v-for to loop over the data and printing it out to the user. The goal is to toggle a class when the user clicks on a specific element inside the table. When i’m trying to add a v-bind:class="{'active' : isActive} it just adds that class to all of them and not the specific.

<table> <tbody> <tr v-for="(item, index) in tableFilter" @click="selectThis(item)" v-bind:class="{'active': isActive}"> <td>{{item.Name}}</td> <td>{{item.Address}}</td> <td>{{item.Telephone}}</td> <td>{{item.Email}}</td> </tr> </tbody> </table> export default { data() { return { isActive: false, data: data } }, methods: { selectThis(val, index) { this.isActive =! this.isActive } }, computed: { tableFilter() { return data; } }
Categories: Software

Set focus on input after it's showed by v-show

Tue, 2017-08-22 20:43

I have a simple form that is hidden when the page is loaded, using v-show. I want to focus the input after showing it. I have a button to call a a method that shows the form and sets the focus to the input using this code:

this.newQuestion = true; //(Form whit v-show:newQuestion) this.$refs.questionInput.focus();

The problem is that the form is showed correctly, but the input isn't focused the first time I press the button, if I press it for a second time when the form is in the page it works. I want to know if there is a way to do this, thanks.

Categories: Software

Security of changing password in vue's component

Tue, 2017-08-22 20:33

I made an component in my SPA application to changing user's password. All my code that is working correctly looks like this:

method which is getting data from form with v-model:

export default { data(){ return { password: { old_password: '', new_password: '', repeat_password: '' } } }, methods: { changePassword() { axios.post('api/change_password', this.password).then( response=> { this.password = { old_password: '', new_password: '', repeat_password: '' }; console.log(response.data.message); }); } } }

then in my controller i receive data and I am validating them in this way:

public function update(Request $request) { $get_user = Auth::user(); $user = User::find($get_user->id); $current_password = $get_user->password; if (Hash::check($request->input('old_password'), $get_user->password) && ($request->input('new_password') == $request->input('repeat_password'))) { $user->update([ 'password' => Hash::make($request->input('new_password')) ]); return response()->json([ 'message' => 'Password updated' ]); } }

My question to you guys is that: Is this method secure? If not could you explain how to do this in better way?

Categories: Software

authentication system using token in nodejs vuejs app?

Tue, 2017-08-22 19:30

I have built an spa using nodejs and vuejs i want to add an authentication system on it, but i haven't done it before hence need some guidance.

the flow will be like : 1) admin will create the profile of the user 2) An email will be automatically sent to the user using sendgrid 3) the email consits of an url with token which expires in 24 hrs the user when click in specific time will be routed to a page where they can create a new password 4) i was planning to use passport for authentication in my app

Is this the right way to do?, also how do i send the token with url and authenticate when i the user clicks

Categories: Software

Vue wait until all images referenced in CSS have loaded

Tue, 2017-08-22 18:36

In my Vue app I have a large image (170K) that is referenced in CSS as a background image. While my app is initially loading, I would like to show a spinner image or div that waits until this image has finished loading. This seems to be the default behavior in Angular2+, how do I achieve the same with Vue?

Categories: Software

Load PDF in modal with Laravel routes and vuejs axios

Tue, 2017-08-22 18:10

I am trying to generate a PDF and open a modal on button click. In the modal the generated PDF should be loaded in the DOM.

To generate the PDF I use axios:

axios.post('/preview', formData) .then(function (response) { this.previewPdf = response.data; }.bind(this));

The generated PDF name is returned in the controller and saved in the this.previewPdf variable.

Then I use laravel URL wildcards to load the PDF in the modal.

<div class="modal-body"> <embed :src="'/preview/' + previewPdf" width="100%" height="600" type='application/pdf'> </div>

And the controller for the route /preview/{pdfname} returns the PDF.

return Storage::disk('local')->get('temppdf/' . $pdfname);

However if I open the modal the PDF seems to be loaded (Network preview):

%PDF-1.7 %���� 2 0 obj <</Type/XObject etc.

But the modal just shows an empty <embed>. Although the src of it is correctly src="preview/pdfname.pdf".

What could cause this issue?

Categories: Software

Filtering data with forms and Vuex without conditionals

Tue, 2017-08-22 18:00

In my component I am looping through a list of items:

<item v-for="item in items" :key="item.id" :item="item"> </item>

I have a getter which based on filter criteria sets state.items:

export const items = state => state.items.filter(item => item.mySex === state.filter);

These are the filter radio buttons:

<input class="form-check-input" type="radio" name="sexFilter" v-model="mySex" id="sex-female" value="1">

And I use watch to dispatch actions:

watch: { mySex(value) { this.$store.dispatch('setFilter', Number(value)); }, },

My problem is that when no filter is applied my getter sends back 0 results. I would like to tackle that without using conditions.

Categories: Software

How to listen to scroll event in a Vue component?

Tue, 2017-08-22 17:50

I can't find a way to actually listen to a scroll event in my component. I tried v-on:scroll="scrollFunction" but it doesn't seem to work.

Does anyone know how to do it?

Thanks!

Categories: Software

Does vue.js update computed properties that depend on methods?

Tue, 2017-08-22 16:56

so in my code, I have a computed value today that allows me to access the current day, month and year, using the following code:

today: function() { var currentDate = new Date(); return { day: currentDate.getDate(), month: currentDate.getMonth(), year: currentDate.getFullYear() }; }

Now as far as my understanding goes, the difference between computed properties and methods is that computed props are cached and only recalculated if their dependencies (for example, a normal property) changed, while methods are fully calculated every time.

Now in my case, there are no dependencies. So, if on initialization, it's the 24th Dec 2017, late at night, and I access today.day a few minutes later when it's the 25th - will I be given the original value or will the value be recalculated?

Technically, no properties are dependencies of this computed property, so nothing changed. According to the following extract from the official guide, today.day should still equal 24.

However, the difference is that computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed.

Categories: Software

Localization Vue.js including data coming from server

Tue, 2017-08-22 16:41

I'm building an app in Vue.js with rest api (server) is in Java.

I implemented Localization using https://kazupon.github.io/vue-i18n and it seems to work fine.

The problem i'm facing now is that when I'm getting data from the server (ie: list of cities) which have to be localizated also; I don't know which approach is better for this.

I thought of few options, having a db table like "id | name", (name has to be localized) the name value could be in json.

{"en": "English name"}, {"fr": "French name"}, {etc...}

Then in Vue.js I could apply list.map and filter by the current locale. But for making dynamic filtering on that set of data I'm kinda stuck.

Do you think that's a good approach? Would it be better to ask the server already in the current locale in each request?

Any ideas?

Thanks in advance!

Categories: Software

vuejs class-component typescript pass class as property

Tue, 2017-08-22 16:29

I am trying to pass a class as a prop:

export default class ModelForm extends Vue { @Prop() model: Model item: Model = new this.model() }

This does not work and typescript wants me to pass the constructor instead of the class:

export default class ModelForm extends Vue { @Prop() modelConstructor: Function item: Model = new this.modelConstructor() }

Is there a way to pass the class itself and then instantiate it?

Categories: Software

Multipage Application VueJs

Tue, 2017-08-22 16:26

Hi!
I'm currently building a large scale VueJs Application and would like to set it up as a Multipage Application, where I have two different Sections (Admin + User), that I would like to load independently, yet share some Components and Services. How would I go about building this sort of Architecture, any Help would be appreciated.

Setting up multiple Webpack Entries as described here: (https://github.com/Plortinus/vue-multiple-pages) works for me but the Problem I'm now encountering is the Authentification since the Vuex Store is deleted on reload/redirect.

Did anyone come across this Problem in the Past? Thanks in Advance

Categories: Software

Pages