Vuejs

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

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

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

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

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

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

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

Make use of v-for key outside of the loop

Thu, 2017-08-10 15:31

i have a simple v-for that renders a list of items inside a select box like this:

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

then i have a button that should remove a specific item, the selected one i want to access his key so i can remove it easy, how can i do that? at the moment my key is undefined, can i use v-model for that?

<button @click="removeStyle(key)" class="btn btn-default btn-xs"> <span class="glyphicon glyphicon-remove text-danger"></span> </button>
Categories: Software

expect reads a wrong value of wrapper.vm.shown

Thu, 2017-08-10 15:17

I'm testing my component and a very strange issue occurred.

Here is my test

import { mount } from 'avoriaz'; let wrapper = mount(MyComponent, { globals: {$route},}); it('the click changes the value of shown', () => { // This passes expect(wrapper.vm.shown).to.equal(false); // the click on this element will turn shown value into true wrapper.first('#my_link').trigger('click'); // the value of shown is indeed true now console.log(wrapper.vm.shown); // LOG LOG: true expect(wrapper.vm.shown).to.equal(true); // expected undefined to equal true });

What's happening and why shown is undefined when passed as argument to expect method and is boolean when displayed through console.log?

Categories: Software

clic triggered twice Vue.js

Thu, 2017-08-10 14:24

I have this code

displayGeneralTip (bool) { this.generalTip = bool } <div v-if="!generalTip" class="sm-exercise-tip sm-exercise-general-tip" @click="displayGeneralTip(true)"> <img src="~assets/exercises/bulb.svg" alt="Ampoule éteinte"> <span>Astuce</span> </div> <div v-if="generalTip" class="sm-exercise-block sm-exercise-general-tip-expand"> <div class="general-tip-bulb-icon"> <img src="~assets/exercises/lighted-bulb.svg" alt="Ampoule allumée"> </div> <div class="sm-exercise-block-tip">Some text</div> <div class="sm-exercise-hide-answer" @click="displayGeneralTip(false)"> <span>Masquer</span> <img src="~assets/exercises/eye.svg" alt="masquer"> </div> </div>

Initially, generalTip is set at false. When clicking on the first div to display text, It works fine. The first block disappear, and the second one appears.

But when clicking on the div to hide answer (sm-exercise-hide-answer), It triggers the method displayGeneralTip with bool false, but just after it triggers the same method with bool true. As if we clicked on the second div and the first one too.

I tried to put the div with text else where in my page, and it works fine. The problem appears when the two divs must be on the same place on the page

Anyone had this problem ?

Categories: Software

How to remove rows from table in Vue component?

Thu, 2017-08-10 13:12

I'm brand new to Vue and have been struggling with this all day. I am trying to build a table using Vue components that can allow users to add and remove rows.

The problem I'm having is the removeRow() fuction is not removing the selected row, it's removing the last row off the table. Can anyone help me out?

Vue.component('newtemplate', { template: `<div> <div> <button class="button btn-xs btn-success" @click="addRow">+</button> </div> <table> <thead> <tr> <th class="col-lg-6 nopadding"><input type="text" value="Col 1" class="borderless nopadding col-lg-6"></th> <th class="col-lg-2 nopadding"><input type="text" value="Col 2" class="borderless nopadding col-lg-12"></th> <th class="col-lg-2 nopadding"><input type="text" value="Col 3" class="borderless nopadding col-lg-12"></th> <th class="col-lg-2 nopadding"><input type="text" value="Col 4" class="borderless nopadding col-lg-12"></th> </tr> </thead> <tbody> <tr v-for="(row, index) in rows" :row="row"> <td> <input type="text" class="form-control nopadding text-center"> </td> <td> <input type="text" class="form-control nopadding text-center"> </td> <td> <input type="text" class="form-control nopadding text-center"> </td> <td> <input type="text" class="form-control nopadding text-center"> </td> <td> <button type="button" class="text-center button btn-xs btn-danger" v-on:click="removeRow(index)">-</button> </td> </tr> </tbody> </table> </div>`, data: function() { return { rows: [{row: ""}] } }, methods:{ addRow(){ this.rows.push({row: ''}); }, removeRow: function(index) { this.rows.splice(index, 1); } } });
Categories: Software

npm run dev command does not work on vuejs' hackernews example

Thu, 2017-08-10 12:16

I am trying to run the vue-hackernews-2.0 example from vuejs' github repository

In setup section it explains how to install the project:

# install dependencies npm install # or yarn # serve in dev mode, with hot reload at localhost:8080 npm run dev # build for production npm run build # serve in production mode npm start

I did npm install. After changing the port to 8888 in server.js I typed "npm run dev" on command line.

> vue-hackernews-2.0@ dev D:\Users\212399486\WebstormProjects\vue-hackernews-2.0-master > node server server started at localhost:8888 DONE Compiled successfully in 16328ms 1:02:18 PM DONE Compiled successfully in 17845ms 1:02:19 PM webpack built bd162a76119031a85eed in 17845ms

When I go localhost:8888 It will just try to load for 1 min and then it fails, without anything on the console.

I thought I should also try "npm run build" and "npm start" so I also used two commands. "npm run build" successfully created the dist file.

But after "npm start" I get this error:

> vue-hackernews-2.0@ start D:\Users\212399486\WebstormProjects\vue-hackernews-2.0-master > cross-env NODE_ENV=production node server module.js:471 throw err; ^ Error: Cannot find module './dist/vue-ssr-server-bundle.json' at Function.Module._resolveFilename (module.js:469:15) at Function.Module._load (module.js:417:25) at Module.require (module.js:497:17) at require (internal/module.js:20:19) at Object.<anonymous> (D:\Users\212399486\WebstormProjects\vue-hackernews-2.0-master\server.js:41:18) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) events.js:160 throw er; // Unhandled 'error' event ^ Error: spawn node ENOENT at notFoundError (D:\Users\212399486\WebstormProjects\vue-hackernews-2.0-master\node_modules\cross-spawn\lib\enoent.js:11:11) at verifyENOENT (D:\Users\212399486\WebstormProjects\vue-hackernews-2.0-master\node_modules\cross-spawn\lib\enoent.js:46:16) at ChildProcess.cp.emit (D:\Users\212399486\WebstormProjects\vue-hackernews-2.0-master\node_modules\cross-spawn\lib\enoent.js:33:19) at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12) npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "D:\\Users\\212399486\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "start" npm ERR! node v6.11.2 npm ERR! npm v3.10.8 npm ERR! code ELIFECYCLE npm ERR! vue-hackernews-2.0@ start: `cross-env NODE_ENV=production node server` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the vue-hackernews-2.0@ start script 'cross-env NODE_ENV=production node server'. npm ERR! Make sure you have the latest version of node.js and npm installed. npm ERR! If you do, this is most likely a problem with the vue-hackernews-2.0 package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! cross-env NODE_ENV=production node server npm ERR! You can get information on how to open an issue for this project with: npm ERR! npm bugs vue-hackernews-2.0 npm ERR! Or if that isn't available, you can get their info via: npm ERR! npm owner ls vue-hackernews-2.0 npm ERR! There is likely additional logging output above. npm ERR! Please include the following file with any support request: npm ERR! D:\Users\212399486\WebstormProjects\vue-hackernews-2.0-master\npm-debug.log

Screenshot of dist folder:

enter image description here

package.json scripts:

"scripts": { "dev": "node server", "start": "cross-env NODE_ENV=production node server", "build": "rimraf dist && npm run build:client && npm run build:server", "build:client": "cross-env NODE_ENV=production webpack --config build/webpack.client.config.js --progress --hide-modules", "build:server": "cross-env NODE_ENV=production webpack --config build/webpack.server.config.js --progress --hide-modules" },
Categories: Software

Vue Js v-model not working with array created in Laravel model

Thu, 2017-08-10 11:50

I'm currently in the process of building a CMS using Laravel and Vue JS which build forms dynamically based on an array of data created in the Laravel model. Here is an example:

class TheBuilding extends Model { protected $fillable = [...]; public function formFields(){ $fields = [ [ 'label' => 'Title', 'name' => 'title', 'component' => 'input_text' ], [ 'label' => 'Content', 'name' => 'content', 'component' => 'input_textarea' ], [ 'label' => 'Main Image', 'name' => 'main_image', 'component' => 'input_single_upload' ], [ 'label' => 'Gallery', 'name' => 'gallery', 'component' => 'input_multiple_upload', 'meta' => [ [ 'type' => 'text', 'name' => 'caption', 'label' => 'Caption' ] ] ], ]; return $fields; } }

Basically this array gets passed into Vue JS and parsed to dynamically display Vue JS form components accordingly. This has been working great but I've come across an interesting issue with the Gallery multiple upload component which needs the ability to assign captions to images.

To fast forward a bit, I'm at the point where I have an array of uploaded files which get iterated through and displayed on the page, and then I have the input textfield for the caption underneath.

Here's my component (edited to show the relevant bits):

<template> <div class="row"> <div v-for="(file, i) in files"> <img :src="file.file" > <div v-for="meta in file.meta"> <input v-if="meta.type == 'text'" type="text" v-model="meta.value"> </div> </div> </div> </template> <script> export default{ computed:{ files(){ let uploads = []; /*this.uploaded is just an array of filenames*/ this.uploaded.forEach((file, i) => { let createdMeta = [ { name:"caption", type:"text", value:'' } ]; uploads.push({file,meta:createdMeta}); }); return uploads; } }, props:{ ... }, mounted(){ //CODE THAT HANDLES DROPZONE UPLOAD }, name: 'InputMultipleUpload', data(){ return { showUploadProgress:true, } } } </script>

The bit I'm focusing on is:

let createdMeta = [{ name:"caption", type:"text", value:'' }];

You'll notice here that I've created that array statically. If I do that, when I type in a caption textbox everything works fine and the caption value gets updated dynamically by v-model as expected. Essentially, I get the desired result and everything is good.

However, if I try and set this this dynamically from the created model ie:

let createdMeta = formFields;

where formFields is the reference to the model array, when I then type in the textbox it updates all other textboxes and values in the files array created. V-Model no longer seems to relate to the specific textbox.

So I guess the question I'm asking is:

a) Why is it behaving that way when I passed in the referenced array

b) Why does it work fine if I just manually create that array?

c) How can I get A to behave like B?

Thanks everyone, happy to clarify anything. I assume i'm missing a piece in the reactivity puzzle.

Cheers, Lew

Categories: Software

.js variables not returning to zero when made equal to 0

Thu, 2017-08-10 10:33

I have various .js functions calculating order sub-totals, tax, and final total price in a modal. The calculations are correct, but the variables don't seem to be cleared on modal exit/modal pop-up. This means that every modal past the first one simply adds their (correct) calculations to the previous ones, rather than starting from zero as I'm trying to make it do.

I've set breakpoints in the .js source, and it tells me that the .js numbers are the one's not zeroing even when there is a set to zero on them right after the number is passed back.

Here is a picture set of the first and second modal call to illustrate this issue (bottom right numbers on both):

first modal second modal

Here is my html, in case it's actually a tag-based issue:

@{ ViewData["Title"] = "Index"; Layout = "~/Views/_Layout.cshtml"; } <div class="col-sm-3">&nbsp;</div> <div class="panel col-sm-6 col-xs-12"> <div class="panel-title text-center" style="padding-top:20px;"> <h3 style="font-weight:bolder">Cart Contents</h3> <img src="/img/cart.png" style="height:10%;width:10%;padding-bottom:5%;" /> </div> <div class="text-center" style="padding-top:10px;"> @{ Dictionary<string, object> cart = Context.Session.Get<Dictionary<string, Object>>("cart"); decimal itemSubTotal = 0; decimal subTotal = 0; decimal itemTaxTotal = 0; decimal taxTotal = 0; decimal salesTaxRate = 0.13M; //m required for a literal decimal orderTotal = 0; } <table class="table table-striped"> <tr style="font-weight:bolder;"> <th class="col-xs-2 text-center">Product Code</th> <th class="col-xs-2 text-center">Qty</th> <th class="col-xs-2 text-center">Item Name</th> <th class="col-xs-2 text-center">Price</th> </tr> @{ if (cart != null) { foreach (var key in cart.Keys) { ProductViewModel item = JsonConvert.DeserializeObject <ProductViewModel> (Convert.ToString(cart[key])); if (item.Qty > 0) { subTotal += item.MSRP * item.Qty; <tr> <td class="col-xs-2 text-center">@item.Id</td> <td class="col-xs-2 text-center">@item.Qty</td> <td class="col-xs-2 text-left">@item.ProductName</td> <td class="col-xs-2 text-center">@string.Format("{0:C}", @item.MSRP)</td> </tr> } } taxTotal += Decimal.Multiply(subTotal, salesTaxRate); orderTotal += subTotal + taxTotal; } } </table> <hr /> <table class="table table-striped"> <tr> <th colspan="4" class="col-xs-4 text-left" style="font-size:large;font-weight:bold;"> Cart Totals </th> </tr> <tr> <td class="col-xs-2 text-right">Subtotal: </td> <td class="col-xs-4 text-left" id="subtotal">@string.Format("{0:C}", @subTotal)</td> </tr> <tr> <td class="col-xs-2 text-right">Tax Total: </td> <td class="col-xs-4 text-left" id="taxtotal">@string.Format("{0:C}", @taxTotal)</td> </tr> <tr> <td class="col-xs-2 text-right">Order Total: </td> <td class="col-xs-4 text-left" id="ordertotal">@string.Format("{0:C}", @orderTotal)</td> </tr> @{ @subTotal = 0; @taxTotal = 0; @orderTotal = 0; } </table> <div class="text-center"> <form asp-controller="Cart" asp-action="AddCart" method="post" role="form"> @if (Context.Session.GetString(SessionVars.User) != null) { <button type="submit" class="btn btn-sm btn-primary" id="modalbtn">Add Cart</button> } &nbsp;<a href="/Cart/ClearCart" class="btn btn-sm btn-success">Clear Cart</a> </form> </div> </div> </div>

And here is the .js file where the calculations are being done:

var link = '/GetOrders'; var detailslink = '/GetOrderDetails/'; var subtotal = 0; var finalPrice = 0; var taxAmount = 0; // register modal component Vue.component('modal', { template: '#modal-template', props: { item: {}, modalItem: {}, details: [] }, }) new Vue({ el: '#orders', methods: { GetOrders: function () { var self = this axios.get(link).then(function (response) { self.orders = response.data; }, function (error) { console.log(error.statusText); }); }, loadAndShowModal: function () { var self = this axios.get(detailslink + this.modalItem.id).then(function (response) { self.details = response.data; self.showModal = true; }, function (error) { console.log(error.statusText); }); }, }, mounted: function () { this.GetOrders(); }, data: { orders: [], showModal: false, modalItem: {}, details: [] } }); function formatDate(date) { var d; if (date === undefined) { d = new Date(); //no date coming from server } else { var d = new Date(Date.parse(date)); // date from server } var _day = d.getDate(); var _month = d.getMonth() + 1; var _year = d.getFullYear(); var _hour = d.getHours(); var _min = d.getMinutes(); if (_min < 10) { _min = "0" + _min; } return _year + "-" + _month + "-" + _day + " " + _hour + ":" + _min; } function calcLinePrice(qtySold, msrp) { var linePrice = qtySold * msrp; subtotal += linePrice; finalPrice += linePrice; return linePrice.toFixed(2); finalPrice = 0; subtotal = 0; } function calcSubtotal() { return subtotal.toFixed(2); subtotal = 0; finalPrice = 0; subtotal = 0; } function calcTax() { taxAmount = finalPrice * 0.13 return taxAmount.toFixed(2); taxAmount = 0; } function calcFinalPrice() { var total = 0; total = finalPrice + taxAmount; return total.toFixed(2); finalPrice = 0; subtotal = 0; }

As you can see, I'm zeroing the finalTotal and subtotal in every calculation in an attempt to figure this out. It seems that no matter what I do, they refuse to zero on anything but page reload. Any help?

Categories: Software

Larevels intended() with vue route

Thu, 2017-08-10 10:32

I am working on a project and am struggling with redirecting to intended location after login. The problem is that Laravel does not include Vues route (anything after #/...) so it always redirects me only to 'domain.com/'

I am using laravel routing only for 'login' 'logout' and '/' and rest of the app is single page utilizing vue routing.

Users of the app are receiving notification emails when they need to take action. Those email contain links to requests where their action is required (e.g. domain.com/#/request/3413). Of course they need to login to be able to access that so they are redirected to login page by laravel (domain.com/login#/request/3413)

After successful login I am trying to redirect them with

return redirect()->intended('/');

But it redirects them to 'domain.com/' instead of 'domain.com/#/request/3413'

Is there any way to make laravel include vues route in that redirect?

Thanks a lot!

Categories: Software

How to add and remove items between select box in vue js?

Thu, 2017-08-10 10:02

Html:

Select box:1

<select v-model="facilitySelected" 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>

Click Events:

<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 Box:2

<select name="facilities" multiple="multiple" id="facilities2" size="4" class="form-control"> <option v-for="facility in selectedFacilities" v-bind:value="facility.value">{{facility.label}}</option> </select>

And the script was,

export default { data(){ return{ facilitySelected:[], availableFacilities: [{ value: 1, label: 'Double (Non a/c)' }, { value: 2, label: 'Premium Double (a/c)' }, { value: 3, label: 'Standard Double (a/c)' } ], selectedFacilities: [], } }, methods:{ addFacilities() { this.selectedFacilities = this.facilitySelected.concat(this.selectedFacilities); }, removeFacilities() { }, } }

Here i have two select boxes with click events in between, I have assigned the values to the variable to the first select box option. My requirement is when i select a option from first select box and click over the addFacilities click event, the data in that particular option should be moved to second select box and when i select option in second select box and click over removeFacilities, the data needs to move to first select box.

For adding first to second i tried with,

addFacilities() { this.selectedFacilities = this.facilitySelected.concat(this.selectedFacilities); },

It moving the data to second select box but that data still remaining in first select box, how should i remove this duplication and here i am using concat to add the data. If i select the option and click addFacilities, that option should be removed from the first select box and vice versa for removeFacilities also.

Categories: Software

Run the method of the Vue component after the external script is loaded

Thu, 2017-08-10 06:37

I am using google maps API, and have created a Component to display the map.

index.html:

<!DOCTYPE html> <html> <head> ... </head> <body> <div id="app"></div> <!-- built files will be auto injected --> <script> function initMap() { console.log('map loaded'); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=googleapikeyxxxx&callback=initMap" type="text/javascript"></script> </body> </html>

GoogleMap.vue:

<template> <div class="google_map" :id="map_name"></div> </template> <script> export default { name: 'google_map', props: ['map_id'], data() { return { map_name: this.map_id + '-map', } }, methods: { create_map() { const element = document.getElementById(this.map_name); const options = { zoom: 14, center: new google.maps.LatLng(51.501527, -0.1921837) }; const map = new google.maps.Map(element, options); const position = new google.maps.LatLng(51.501527, -0.1921837); const marker = new google.maps.Marker({ position, map }); } }, mounted() { this.create_map(); } } </script>

The problem is, the component is rendered before the google maps API is loaded. How can I display after the google maps API has been loaded?

Categories: Software

Binding Styles in Vue.js

Thu, 2017-08-10 06:02

New to Vue.js 2. I am trying to give each div their own unique style in a v-for loop. What am I doing wrong? What is a better way to accomplish what i'm trying to do?

var tables = new Vue({ el: '#table', data: { tables: [ {name: 'iPhone', left:1, top:0}, {name: 'Mac', left:150, top:0} ] } }) .table-div { width:100px; height: 100px; border:1px solid black; position: absolute; } <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div id="table"> <div v-for="table in tables"> <div class="table-div" v-bind:style="{top: table.top, left: table.left}">{{table.name}}</div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script> </body> </html>

Categories: Software

How to get both value and text from select in vue js?

Thu, 2017-08-10 05:55

Html:

<select v-model="facilitySelected" name="facilities" multiple="multiple" id="facilities" size="4" class="form-control"> <option value="1">Double (Non a/c)</option> <option value="2">Premium Double (a/c)</option> <option value="3">Standard Double (a/c)</option> </select>

Click event:

<a @click="addFacilities" class="btn btn-default add_option" rel="facilities2" id="add"><i class="fa fa-arrow-right"></i></a>

Script:

export default { data(){ return{ facilitySelected:[] } } methods: { addFacilities() { this.facilitySelected; console.log(this.facilitySelected); } } }

Here i have a list of select with options, When i click on the addFacilities, the value of the selected option only making as output in console.log, i need to have both value as well as the text in the option to be come out through console.log.. How to get both the value and the text when i click on the addFacilities?

Categories: Software

Is there any way to pass the html tag to a function in vuejs?

Thu, 2017-08-10 03:32

I have an html code like this in vuejs:

<img v-if="shouldBePrinted(tag)" src="someimage.jpg">

I would like to pass the tag itself (img) to the function shouldBePrinted to determine if it should be showed.

Is there any way to do this?

I tried with a ref like this but, in this case, I would like to avoid it:

<img ref="imgRef" v-if="shouldBePrinted(this.$refs.imgRef)" src="someimage.jpg">
Categories: Software

Generating select options with v-for using an object

Thu, 2017-08-10 02:42

I have an object that contains user names in this structure:

clients: { 1: { first_name:"John" last_name:"Doe" middle_name:"A" }, 1: { first_name:"Jenny" last_name:"Doe" }, }

I want to loop though them in a select input as options

<option v-for="(value, client, index) in clients" :value="">{{ value }}</option>

I came until here, but I couldn't figure out how to organize the string properly. Maybe, is there a way to parse it in computed properties so I can have room to put code?

If I could use something like this, I think it would work, but couldn't figure out how to do it like this either.

computed:{ clientNameOptions() { for (const key of Object.keys(this.clients)) { return `<option value="` + this.clients[key].first_name + ' ' + this.clients[key].middle_name + ' ' + this.clients[key].last_name + `"></option>` } } }

What is the proper way of achieving it?

Categories: Software

How do I change the value of a textarea when using a reuseable component?

Thu, 2017-08-10 01:04

I need to change the text within a specific component's textarea when requirements are met from entering text into a different components textarea. I've tried to create a simple example to show the issue. my main issue is targeting the correct component and editing its text that shows up dynamically.

Parent Component

<template> <reuseableComponent input-type="textarea" v-model="Example1"> </reuseableComponent> <reuseableComponent input-type="textarea" v-model="Example2"> </reuseableComponent> <template>

Reuseable Component

<textarea v-model='taValue' @input='$emit("input", taValue)'> </textarea> exampleMethod() { if(value) { //change text in Example2 textarea instance. } }
Categories: Software

Pages