Software

Select input fail with autoIncrement Id

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

I am using VueJs and C# to build a simple aplication, my use case at the moment is to build a select list that has some styles, basicly i can add and remove the styles. My styles model is simple it just has a key(Id that is auto increment in the backend) and a string(that represents the style i want.

Everytime i fire the page, i use a mounted function that should load the styles that already exist on the database, like this:

mounted() { this.$http.get('http://localhost:16339/api/Styles/Getstyles') .then(response => { var vm = this; response.body.forEach(function (style) { console.log(style) vm.$store.commit("initializeStyles", style); }); }, error => { console.log(error); });

every style is a json object like this: {"Id": thStyleId,"style":theStyleName}

as you guys can see i am using vuex, when i load my data i send it to my styles array that is in the store of vuex, since it is shared by multiple components.

the array looks like this:

tableStyles: [],

simple, my html that handles the input of the select list is like this:

<div class="col-md-4"> <select class="form-control" v-model="tableStyle"> <option v-for="(item,key) in tableStyles" :value="item.Id"> {{ item.style }} </option> </select> </div>

i use the id as a key, so i can know each items Id, now i add and remove a style this way:

removeStyle() { var vm = this; console.log(this.tableStyle); if (vm.tableStyle == 1) { alert("CMFtable is the default template you can't remove it, just stop trying!"); } else { vm.$http.delete('http://localhost:16339/api/Styles/DeleteStyle/' + vm.tableStyle) .then(response => { this.getStyleIndex(vm.tableStyle); }, error => { console.log(error); }); } }, addNewStyle() { var Id = this.tableStyles[this.tableStyles.length - 1].Id + 1; var newStyleObj = { 'Id': Id, 'style': this.newStyle }; var vm = this; vm.$http.post('http://localhost:16339/api/Styles/PostStyle/', newStyleObj) .then(response => { vm.newStyle = ""; vm.tableStyles.push(newStyleObj) }, error => { console.log(error); }); }, getStyleIndex: function (tableStyle) { this.tableStyles.forEach(function (element, index) { if (element.Id == tableStyle) { vm.tableStyles.splice(index, 1); } }); }

my issue about this, is that everytime i add a new style and try to remove it, it doesn't work, because the Id is autoIncrementing in the server side, so if i remove it next time instead of being Ids: 1,2. it will be: 1,3 (considering i removed the object with id 2.

This only happens if i try to insert and remove without refreshing the page, because if i refresh it passes the id that is in the database, in my code when i add to the select list i just get the last and increment and send it.

So i thaught about some solutions:

  • Chaning the auto-increment to manual increment (can have a lot of issues with that, one of them is concurrency;

  • trying to refresh the select list, not incrementing the list but refreshing after the insert

so i need some feedback about my issue, if i am in the right way, or if there is another solution to solve my problem.

Thank you for your patience and time :)

Categories: Software

Is it possible to globally remove a vue component from the global registry?

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

I would like to remove a components from Vue at runtime that was previously registered with Vue.component(name, {...}), is this possible ?

We are creating a number of components on the fly in a live development setting and would like to remove old components from memory.

Or is it possible to alter the child components registered with a component at runtime ? Only affecting new component instances built after that of course or refreshed manually.

Categories: Software

Vue.js Passing Data to Another Page

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

I'm fetching data from REST api using vue-resource and showing the lists of data in the landing page. User sees the Title and short description, and when clicks on the Title user should go in that page. When I'm using a tag for the URL it's working fine, but when using router-link it doesn't show the Title.

HTML

<div class="food_list_content_bg" id="app-router"> <div class="food_list_content"> <h3><a href="">Article Name</a></h3> <router-link to="restaurant-profile.html"><h5>{{ rest.title.rendered }}</h5></router-link> <ul v-for="csn in rest.cuisine_type"> <li>{{ csn.name }}</li> </ul> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> </div> <div class="single_food_list_footer_top"> <a href=""> <ons-icon icon="fa-user" size="20px" fixed-width="false"> </ons-icon> </a> <div class="publisher-name"> <strong>Added By</strong> <p>Board Name</p> </div> </div> <div class="single_food_list_footer"> <p>Picked For</p> <strong>"ITEM"</strong> </div> </div>

JS

(function($){ var config = { api: { restaurants: 'data-url' }, }; var restaurants = new Vue( { el: '#post-list-tmpl', data: function() { return { restaurant: [], cuisin: [] } }, mounted: function () { this.getRestaurant(); }, methods: { getRestaurant: function () { var self = this; $.get( config.api.restaurants, function(r){ self.$set(self, 'restaurant', r); }); } } }); var router = new VueRouter({ mode: 'history', routes: [ { path: 'restaurent-profile.html', name: 'restaurent', component: restaurent }, ] }); new Vue({ router, }).$mount('#app-router'); })( jQuery );

Here's JSFiddle. How to get it work??

Also I need to pass the id of the clicked item to the next page restaurant-profile.html. Is there any to pass that ??

I'm using Vue.js directly including the script. I would prefer a way to do these without installing Vue.js if possible.

Categories: Software

How to send password to server using vue or javascript?

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

I have created vue components for login and registration. How do I send password to the server?? Should I just encrypt the password using bcrypt on the client side and then send it to Laravel or should I just send the plain password to Laravel and use bcrypt($request->get('password')); What would be a good option?

If I should encrypt the password in the vue component, what package/function should I use so that it will encrypt the password in the same way as Laravel/PHP does??

Categories: Software

How to show image and percent of page loaded in vuejs 2?

Vuejs - Fri, 2017-08-11 07:18

How can I show an image and percent of page loaded before it's fully loaded? Like http://vyctoire.com

And how can I re-use it in Ajax calls?

Categories: Software

How to remove the selected data from an array in vue js?

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

I am in the need of splicing a data from the array, for which i have used the following,

Html:

<div id="app"> <select v-model="facilityAvailable" name="facilities" multiple="multiple" id="facilities" size="4" class="form-control"> <option v-for="availability in availableFacilities" v-bind:value="availability">{{availability.label}}--</option> </select> <a @click="removeFacilities" class="btn btn-default remove_option" rel="facilities2" id="remove"><i class="fa fa-arrow-left"></i></a> <a @click="addFacilities" class="btn btn-default add_option" rel="facilities2" id="add"><i class="fa fa-arrow-right"></i></a> <select v-model="facilitySelected" name="facilities" multiple="multiple" id="facilities2" size="4" class="form-control"> <option v-for="facility in selectedFacilities" v-bind:value="facility">{{facility.label}}</option> </select> </div>

Script:

new Vue({ el: "#app", data: { facilityAvailable: [], facilitySelected:[], availableFacilities: [{ value: 0, label: 'Double (Non a/c)' }, { value: 1, label: 'Premium Double (a/c)' }, { value: 2, label: 'Standard Double (a/c)' } ], selectedFacilities: [], }, methods: { removeFacilities(index) { this.availableFacilities = this.facilitySelected.concat(this.availableFacilities); this.selectedFacilities.splice(index,1); }, addFacilities(index) { this.selectedFacilities = this.facilityAvailable.concat(this.selectedFacilities); this.availableFacilities.splice(index,1); } } })

Here i am doing like transfer of one element from one select box to the other to another select box, for which i have used concat for adding to another and splice to remove that element.. Everything was fine upto this. But when i splice , it is splicing in the order of 0,1,2 i need to splice based on the index number of that particular element. In clear, i can select and remove the element in any order for which that particular element needs to be removed and gets transferred into second select box, whereas now if i remove it in the order as it was , its working fine but whereas if i change the order and splice its not working. Also when i select multiple elements and remove, the same thing happening. Kindly help me to solve this issue.

The fiddle link was, https://jsfiddle.net/pmvp3td6/

Categories: Software

Activating Vue that is within a template rendered by a Controller

Vuejs - Fri, 2017-08-11 04:42

I am stuck in a situation where the (Laravel) Controller is providing a view to insert into the frontend using Ajax like this:

MyController.php

return Response::json(['html' => View::make('my_blade_view', [ 'items' => $items ])->render()]);

Within my_blade_view.blade.php, I need to add some Vue.js functionality, like this:

my_blade_view.blade.php

<div v-on:click="myVueMethod"></div>

The problem is, when the Ajax call completes, although the HTML from my_blade_view.blade.php is successfully inserted into the page (which is another Blade view), the v-on:click functionality does not run. I am wondering if there is a way I can tell the Vue instance to re-process the page when the Ajax call completes so that it picks up the new Vue code I have added in the template which was rendered by the Controller?

Thank you.

Categories: Software

Unknown custom element: did you register the component correctly in vue 2

Vuejs - Fri, 2017-08-11 04:23

In my laravel vue 2 project, I am getting this error. For recursive components, make sure to provide the "name" option.

I am trying to use one components inside another.

Child component that I want to insert is located at sign/One.vue I am trying to show this components in reg components located inside components folder

<script> import One from './sign/One.vue'; export default { data(){ return { } }, components: { 'one': One } } </script

The trying to use this component like <one></one> and this generate Unknown custom element: <one> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

In my last project I did similar set up and it worked but this time not working..

In my app.js file I have

Vue.component('reg', require('./components/reg.vue')); const app = new Vue({ el: '#app' });
Categories: Software

Why is v-model not showing up? Need to show value when in edit mode on form

Vuejs - Fri, 2017-08-11 02:43

Hey I'm a front end developer looking to integrate some back end data that is using vue JS, which I am very new to.

I have a form, and when the user clicks "edit" I am showing that same form but I want the values to be populated.

Here is the relevant JS:

$(document).ready(function() { new Vue({ el: 'body', data: { editMode: false, challenge: null, challenges: <%= raw @campaign.challenges.to_json(include: [:challenge_tags, :challenge_filters], methods: [:has_link, :encoded_link, :is_active, :contact_count, :total_clicks, :default_image, :completions, :total_targeted, :total_contacts]) %>, }, methods: { edit: function(challenge) { this.editMode = true; this.challenge = challenge; ** } } }) });

** this was a suggestion but it didn't seem to work.

Here is the HTML:

<input class="input" type="text" placeholder="challenge name" v-model="challlenge.name">

This, for example, is working correctly:

<span v-if="editMode">Edit</span>

It is ideal to make it work with v-model.

Any advice helpful!

Categories: Software

How do I use SASS the "normal way" with vue.js?

Vuejs - Thu, 2017-08-10 22:58

Up till now, I've used sass together with Grunt, the result being that I compile x .scss files into style.css.

I've only done one project in React and it's my first time working with Vue.js, so there a a few things I'm trying to understand.

If I want to include css styling in the same file as my Vue component, I can simply use

<style lang="sass"> @import '_card.scss' // Custom CSS code here </style>

From what I understand, Vue takes all the styling from all the .vue files and compiles it into style.css. But since I'm not sure, I ask this;

  1. Are Vue components called in runtime and does that mean that specific parts of styling is compiled instead of loading all styling in one file?

  2. I'm not a big fant of putting styling inside Vue component files. How can I load global styles? If I remember correctly, I had to load the css file in each React component and I don't see the point in this. I just want to load the style in the header.

Categories: Software

Why use components in Vue.js or React?

Vuejs - Thu, 2017-08-10 22:30

So after trying out Vue.js for a little while, it got me thinking...Why do we have to use components? I don't understand the hype behind them as I can just take a for loop and create a div and get the exact same output as if I were using components.

Vue.js's documentation even says:

Components are one of the most powerful features of Vue. They help you extend basic HTML elements to encapsulate reusable code.

But again, it seems it can be done with for loops what Components give you.

The same goes for React as well.

If someone can explain it better, I am all ears.

Thanks.

Categories: Software

Using Laravel Mix with Vue & Electron

Vuejs - Thu, 2017-08-10 21:11

I completed my first Electron app earlier this year using Vue.

I'm using Laravel Mix to compile my applications assets, which works absolutely fine until I need to use the main Electron process.

What I'm trying to do is detect when the main process is resumed after being asleep with the following in my main.js

mb.on('ready', () => { electron.powerMonitor.on('resume', () => { mb.window.webContents.send('resume'); }); });

So when the system is resumed, I'm sending an event ready for consumption in the renderer.

Here is my main app.js for my Vue application.

mounted: function() { var self = this; require('electron').ipcRenderer.on('resume', (event) => { if(self.socket.connected) { self.$store.dispatch('socket/reconnect'); } }); },

I believe my code is correct, but I'm unable to compile my assets with Laravel Mix.

When I compile using npm run prod I get the following error.

This dependency was not found:

  • fs in ./~/electron/index.js

I then tried to install fs (even though I don't think it's necessary) with npm install --save fs but the problem still persists.

After more searching around, some people were suggesting to use the following in my webpack config. So I added it to my webpack.mix.js, leaving my entire Laravel Mix config looking like so:

const { mix } = require('laravel-mix'); mix.js('src/js/app.js', 'app/assets/js'); mix.sass('src/sass/app.scss', 'app/assets/css').options({ processCssUrls: false }); mix.webpackConfig({ target: "electron-renderer" });

But now I get a different error.

This relative module was not found:

  • ./package in ./~/got/index.js

And this is where I'm stumped. I have no idea what to search for and would love if someone could help ease me into the right direction.

Thanks in advance.

Categories: Software

Replicate portion of webpage in new site (tips for injecting dom and style scoping)

Vuejs - Thu, 2017-08-10 20:53
Scenario

Suppose I have a web service capable of fetching a webpage and its static assets (e.g. using PhantomJS). I want to be able to serve the static DOM sub-structure (e.g. everything under the #content div) along with its styling to a new site that shows the extracted webpage on the left side along with the amazing results of my super-amazing awesome machine-learning algorithm for extracting information from webpages on the other side.

Question

Supposing I can send down the HTML sub-structure, CSS, and other asset files down from the server, how do I go about injecting the HTML substructure into a div on my page while scoping the styling?

<!-- partially modified content pulled from another site --> <div id="content"> <!-- I might pull stylesheets from head of source site --> <!-- and inject them in content? Or should I just keep --> <!-- track of styles separately and manually inject them? --> <link rel="stylesheet" type="text/css" href="theme.css"> <img src="new/path/to/static/resource/that/i/saved"/> </div> <!-- my own web page with stuff etc --> <div id="left"> <!-- INSERT CONTENT DIV AND OTHER ASSETS HERE --> </div> <div id="right"> <!-- here I have Vue components and other page interaction stuff --> </div>

Currently I'm using VueJS for my webpage. I know I can do style scoping using Vue components -- maybe there is a way to leverage that? But I really want to know how to solve this problem in a general, framework-agnostic way. I'm too paralyzed by all these things I think could go wrong to even start...

Categories: Software

Selected options to display image

Vuejs - Thu, 2017-08-10 20:15

Hello what i am trying to do is when user select SILVER from select input to display an image and a price, if user select gold a golden ring with new price to display.[i am new in vue.js sorry guys! ] Here is my code:

<div class="hello"> <select v-model="selected"> <option v-for="option in options" v-bind:value="option.value"> <img :src="options.value" width="100%" v-if="option in options"> {{ option.text }} </option> </select> <span>Selected: {{ selected }}</span> </div> <script> export default { name: 'hello', data () { return { msg: 'BoostMe', selected: 'A', options: [ { text: 'One', value: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTKv4- hzPfbogecrmFiBXb2F4Ps9bmFM7gpD_2JM31eWiMIs7RvmmriQuw' }, { text: 'Two', value: 'B' }, { text: 'Three', value: 'C' } ] }
Categories: Software

vuejs <router-link> component keeps the link to the root path always active

Vuejs - Thu, 2017-08-10 19:17

I have my navigation like this

<nav> <ul class="nav nav-list"> <router-link tag="li" to="/"><a href="#">Home</a></router-link> <router-link tag="li" to="/page1"><a href="#">Page1</a></router-link> <router-link tag="li" to="/page2"><a href="#">Page2</a></router-link> </ul> </nav>

I want the link to Page1 to be active when ever am in page1 and same for Page2. It is working fine, the links are been activated when I navigate to the pages BUT the problem is that to link to the root (/) page is always active even when I leave the page.

Categories: Software

how to create a 404 component in vuejs using vue-router

Vuejs - Thu, 2017-08-10 18:50

Am new to vuejs and am working on my first project with vue. I just wondering how I will route to my 404.vue component when the requested url is not found.

Any Idea?

Categories: Software

how can I make this specific format with moment

Vuejs - Thu, 2017-08-10 18:48

I need output like this:

2017-08-11T16:11:00.000Z

I am not sure what this format is called. It seems that there are atleast two variations of this kind of format, the one above and the one that looks like:

2017-08-11 16:11:00+00:00

Is it the same thing? Why two variations?

Now to my problem, I am working with Vue2 and specifically I am using this component:

http://element.eleme.io/#/en-US/component/datetime-picker

When it renders date to the user this component displays in this format: 2017-08-11 18:11:00

Behind the scene if I inspect the component value using Vue debugger it is stored like 2017-08-11T16:11:00.000Z

If you notice on that value it is actually 2 hours offset, I guess that this vue component internally stores value in UTC time based on what user picked and users timezone?

I got this reply from creator of this component when I asked him about what format value is stored inside component:

The value of DateTimePicker is a Date object. You can format it to whatever form you like before sending it to the server.

When I initialize this component I do it like this:

<el-date-picker v-model="dateTimePicker" format="yyyy-MM-dd HH:mm" type="datetime" size='small' placeholder="Pick a date"> </el-date-picker>

dateTimePicker variable is initialized like this:

dateTimePicker: moment.utc(this.initPublishedAtDate, 'YYYY-MM-DD HH:mm').local().format('YYYY-MM-DD HH:mm')

dateTimePicker gets assigned date from server that is transformed to correct local time from UTC time stored on server.

Now everything is fine, user sees correct time upon loading something he created before, but now if user tries to save whatever he is working on, client will send whatever is in dateTimePicker and currently on fresh page dateTimePicker will be in yyyy-MM-dd HH:mm format

This is of course because user has not used picked any new time and datepicker component has not updated dateTimePicker variable with new correctly formatted value that my server expects.

Now server will receive wrong time which is X hours offset and save incorrect time to db. Now if user refreshes the page the time will be wrong. Each time user saves to server without touching datepicker component, date will get offset each time and so on.

Option 1: How can I send correct time to server if user has not messed with datepicker component and datepicker has not inserted correctly formated time?

Option 2: Could I perhaps initialize datepicker component with this format: 2017-08-11T16:11:00.000Z so that even if user does nothing with it and data is sent to server upon save, server will receive correct time.

If I want to do it with second option, how do I produce that format when I initialize dateTimePicker variable with date from server.

Thanks for suggestions.

Categories: Software

Vue multiple api includes

Vuejs - Thu, 2017-08-10 17:13

Hello I'm trying to display google map and I also have input field. But when I run the code I get this: You have included the Google Maps API multiple times on this page

import Vue from 'vue' import App from './App.vue' import VueGmaps from 'vue-gmaps' import * as VueGoogleMaps from 'vue2-google-maps'; Vue.use(VueGoogleMaps, { load: { key: 'AIzaSyCetTFERhTQZDUT1C7GNvElGdsfpVZ98lQ', libraries:['places'], version:'3' // libraries: 'places', //// If you need to use place input } }); Vue.use(VueGmaps, { key:'AIzaSyCetTFERhTQZDUT1C7GNvElGdsfpVZ98lQ', libraries: ['places'], version: '3', }) /* eslint-disable no-new */ new Vue({ el: '#app', render: h => h(App) })
Categories: Software

Set focus on a input control contained in a second level bootstrap modal

Vuejs - Thu, 2017-08-10 17:01

I'm using Vue.js 2.1.10 and Bootstrap 3.3.7 to show a modal that opens another modal dialog. Each modal dialog is contained in a distinct component. Inside the 1st component, there is a reference to the 2nd component (select-travler).

According to the Bootsrap documentation, I have to set the focus by listening to the event shown.bs.modal. This works great to set the focus on an input control contained in the 1st modal. Problem: this way doesn't work when the modal is above another modal.

The 1st modal component looks like this:

<template> <div ref="tripEdit" class="modal fade" role="dialog"> <!-- Inbeded component --> <select-travler ref="selectTravler"></select-travler> <!-- /Inbeded component --> <div class="modal-lg modal-dialog"> <div class="modal-content"> <div class="modal-body container form-horizontal"> <div class="form-group"> <label for="travler_name" class="control-label"> Travler's name </label> <input id="travler_name" ref="travler_name" v-model="travler_name"/> </div> </div> </div> </div> </div> </template> <script> export default { data () { return { travler_name: null, } }, methods: { show (operationType) { $(this.$refs.tripEdit).modal('show'); let that = this; $(this.$refs.tripEdit).on('shown.bs.modal', function () { $(that.$refs.travler_name).focus(); }); if (operationType === 'newTravel') { this.$refs.selectTravler.show(); } }, }, } </script>

The 2nd component contains a similar layout with the following show method:

show () { $(this.$refs.selectTravler).modal('show'); let that = this; $(this.$refs.selectTravler).on('shown.bs.modal', function () { $(that.$refs.people_names).focus(); }); },

When the 2nd modal opens, the focus is still on the 1st modal behind the 2nd modal dialog (I can see the caret blinking in travler_name). How can I set the focus on people_names when the 2nd modal is shown?

Categories: Software

Vue.js: Cannot access data from function / methods

Vuejs - Thu, 2017-08-10 16:04

I am getting value as undefined when I try to access this.perMonth from fnTwo() and fnThree() but works in fnOne(). I can run a function from data(){} and can return some values but cannot return that's in data(){} eg.this.perMonth (check fnThree())

Vue.component('BuySubscription', { template: '#buy-subscription', data() { return { perMonth: 19, valFromFnTwo: this.fnTwo(), valFromFnThree: this.fnThree() } }, methods: { fnOne() { console.log("from fnOne: get data > perMonth: " + this.perMonth); return this.perMonth }, fnTwo() { console.log("from fnTwo: get data > perMonth : " + this.perMonth); return this.perMonth }, fnThree() { console.log("from fnThree: get data > perMonth " + this.perMonth); console.log("from fnThree: get data > valFromFnTwo: " + this.valFromFnTwo); return 123 // retruns static value } } }); new Vue({ el: '#app', }); body { font-family: arial; font-size: 12px} p {margin: 0} <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script> <div id="app" class="col-lg-6 d-flex align-items-center"> <buy-subscription></buy-subscription> </div> <script type="text/x-template" id="buy-subscription"> <div> <p>value from data > perMonth: {{perMonth}}</p> <p>value from data > valFromFnTwo: {{valFromFnTwo}} <span style="color: red"> <-- getting Undefined here (see console)</span></p> <p>value from fnOne(): {{fnOne()}}</p> <p>value from fnTwo(): {{fnTwo()}}</p> <p>value from fnThree(): {{fnThree()}}</p> </div> </script>

Categories: Software

Pages