Software

VueJs adding new key to object reference issue

Vuejs - Mon, 2017-09-11 23:23

I have an issue when adding a new key to an object and then dynamically modifying the fields associated.

For example add a new column, set column name to "url", then attempt to update the value of url for row 1. In my example the value does not actually update even though the field has v-model="row[field.name]. Is there something I should do to make sure row[field.name] is changed when field.name changes

Code: https://codepen.io/RuttyJ/pen/zdgbPB

<table> <thead> <tr> <template v-for="(field, f) in fields"> <th> <flex-row> <flex-column style="width: 100%;"> <flex> <input type="text" :value="field.name" @input="updateField(f, 'name', $event.target.value)" style="width:100%"> </flex> <flex style="width: 100%;"> <select :value="field.type" @change="updateField(f, 'type', $event.target.value)" style="width:100%"> <option v-for="fieldType in fieldTypeOpts" :value="fieldType.value" :selected="fieldType.value == field.type">{{fieldType.label}}</option> </select> </flex> </flex-column> <flex> <button @click="removeField(f)" style="height:100%;">X</button> </flex> </flex-row> </th> </template> <td> <button @click="newField()">+</button> </td> </tr> </thead> <tbody> <tr v-for="(row, r) in rows"> <td v-for="field in fields"> <template> <template v-if="'checkbox' == field.type"> <input type="checkbox" style="float:right;" v-model="row[field.name]" > </template> <input type="number" v-else-if="'number' == field.type" style="width:100%" :value="row[field.name]" @input="updateRow(r, field.name, $event.target.value)"> <input type="text" style="width:100%" v-else v-model="row[field.name]"> {{field.name}} <pre>{{field}}</pre> <pre>{{row}}</pre> </template> </td> <td><button @click="removeRow(r)">X</button></td> </tr> </tbody> <tfoot> <tr> <td v-for="(field, i) in fields"> </td> <td> <button @click="newRow()">+</button> </td> </tr> </tfoot> </table>

FYI i tried both with v-model and value/update()

Categories: Software

TypeError: __WEBPACK_IMPORTED_MODULE_0__api_user__.a.login(...) is undefined

Vuejs - Mon, 2017-09-11 23:16

In my Vue.js project I have the following files:

src/services/http.js

import axios from 'axios' export const HTTP = axios.create({ baseURL: `http://localhost:3000/api/`, responseType: 'json' })

src/api/user.js

import { HTTP } from '@/services/http' export const user = { login (email, password) { HTTP.post('v1/login', { email: email, password: password }) } }

src/store/user/actions.js

import {user} from '@/api/user' export const actions = { loginUser ({ commit }, params) { user.login(params.email, params.password) } }

When I run my code it returns me following error:

TypeError: __WEBPACK_IMPORTED_MODULE_0__api_user__.a.login(...) is undefined
Categories: Software

Using v-model with a prop on VUE.JS

Vuejs - Mon, 2017-09-11 23:05

I'm trying to use a data coming from a prop with v-model, the following code works, but with a warning.

<template> <div> <b-form-input v-model="value" @change="postPost()"></b-form-input> </div> </template> <script> import axios from 'axios'; export default { props: { value: String }, methods: { postPost() { axios.put('/trajectory/inclination', { body: this.value }) .then(response => { }) .catch(e => { this.errors.push(e) }) } } } </script>

The warning says:

"Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "value"

So I changed and now I'm using a data as the warning says.

<template> <div> <b-form-input v-model="_value" @change="postPost()"></b-form-input> </div> </template> <script> import axios from 'axios'; export default { props: { value: String }, data() { return { _value: this.value } }, methods: { postPost() { axios.put('/trajectory/inclination', { body: this._value }) .then(response => { }) .catch(e => { this.errors.push(e) }) } } }

So now the code it's not working and the warning says:

"Property or method "_value" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option"

Any idea how to fix the first code to suppress the warning? (or some idea on how to fix the second code?)

Obs.: b-form-input it's not my componente, this is the Textual Input from Boostrap-Vue (Doc for b-form-input)

Categories: Software

How can I pass properties to a component which is called by router in Vue Js

Vuejs - Mon, 2017-09-11 21:58

I am new to VueJs and I have a problem with two components. I am trying to display a component with vuejs router and I must pass properties to that component and since it's not a child of that component (it's in different directory), how can I pass data to that component? For example:

This is a Parent component:

<template> <div class="container"> <router-link to="/Form"></router-link> </div> </template> <script> export default{ data(){ return{ values: {val1: 123, val2: 321} } } } </script>

This is a components that needs properties, Form component:

<template> <div class="container"> <form> <input type="text" v-model="values.val1"/> <input type="number" v-model="values.val2"/> </form> </div> </template> <script> export default{ props: { values: { type: Object } } } </script>
Categories: Software

Vue.js not persisting select box info in Rails app

Vuejs - Mon, 2017-09-11 19:24

I have the following select box in my Rails app:

<div id="vue-element"> <strong><%= f.label :property_type %></strong><br> <%= f.select(:property_type, options_for_select(@types.map {|type| [type.titleize, type]}, listing.property_type), 'v-model': 'propertyType') %> </div>

but when I try to display the content of propertyType on the same page, Vue is not rendering the selected entry:

{{ propertyType }}

This is how I instantiate vue.

new Vue({ el: '#vue-element', data: { propertyType: undefined } })

Any idea why this may be or how I can debug this? Thanks in advance!

Categories: Software

Electron vue scaffold throwing errors

Vuejs - Mon, 2017-09-11 18:35

I generated the electron-vue scaffold with the vue-cli using vue init simulatedgreg/electron-vue After running yarn I started the application with yarn run dev. By default I get these errors:

? Electron ------------------- Debugger listening on ws://127.0.0.1:5858/189cf481-dd71-43bf-be88-90673ee0aae1 For help see https://nodejs.org/en/docs/inspector ? ---------------------------- ? Electron ------------------- [10928:0911/182704.656:ERROR:CONSOLE(7323)] "Extension server error: Operation failed: : has no execution context", source: chrome-devtools://devtools/bundled /inspector.js (7323) ? ---------------------------- ? Electron ------------------- [10928:0911/182705.653:ERROR:CONSOLE(7323)] "Extension server error: Operation failed: : has no execution context", source: chrome-devtools://devtools/bundled /inspector.js (7323) ? ---------------------------- ? Electron ------------------- [10928:0911/182706.654:ERROR:CONSOLE(7323)] "Extension server error: Operation failed: : has no execution context", source: chrome-devtools://devtools/bundled /inspector.js (7323) ? ----------------------------

On top, the application takes almost 30 seconds to load. Before that I just see the Electron / Chrome Debugger window but they are not filled with any content. This loading behavior is still given when I use yarn build to create and run the packaged electron application.

Any idea how to fix this?

Categories: Software

How can I reset data in child component from parent component on vue.js 2?

Vuejs - Mon, 2017-09-11 18:31

My parent component like this :

<template> <div ref="modal" class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content modal-content-data"> <form id="form-data"> ... <location-select .../> ... </form> </div> </div> </div> </template> <script> import LocationSelect from './LocationSelect.vue' export default{ name: 'CartModal', components:{ LocationSelect, }, mounted(){ $(this.$refs.modal).on('hidden.bs.modal', () => { Object.assign(this.$data, this.$options.data()) }) } } </script>

If modal hidden, it will reset data in parent component and it works

I want to reset data also in child component

I try like this :

<template> <select class="form-control" v-model="selected" ...> ... </select> </template> <script> export default{ name: 'LocationSelect', ... created() { $(this.$parent.$refs.modal).on('hidden.bs.modal', () => { Object.assign(this.$data, this.$options.data()) }) } }; </script>

But it does not work

The child component no reset the data

How can I solve this problem?

Categories: Software

Vuex - Shared server side state?

Vuejs - Mon, 2017-09-11 18:16

I am modifying hacker-news example and I added notifications component (If fetching external data goes wrong: save notification with error in vuex, after user reads it and clicks X remove it from vuex state). Looks like this:

[NOTIFY] (state, message) { state.data.push(message) }, [READ_NOTIFICATION] (state, index) { state.data.splice(index, 1) }

Problem: When data is being fetched and state is being set on server, it keeps error there in global state forever, which means that if I open new browser I will get the same old error from previous session.

Shouldn't server-side vuex state reset on every request? What am I missing?

Categories: Software

Vuejs proxy not working with webpack template

Vuejs - Mon, 2017-09-11 18:04

I am developing a vuejs project with the webpack template on localhost i.e. url: localhost:8080 but I have an express server running in https://foo.bar.com

In the past, I have been making a direct request to the express server by disabling CORS, but now I am trying to make a request via proxy.

According to this API Proxying During Development I have added the following to my config/index.js

proxyTable: { // proxy all requests starting with /api to jsonplaceholder '/': { target: 'https://foo.bar.com', changeOrigin: true, pathRewrite: { '^/': '' } }

And in my login page components/login.vue

I have something like this:

... methods: { Login(){ // trying 3 times with different urls api.request('post', 'login', {email, password}).then().catch() api.request('post', '/login', {email, password}).then().catch() api.request('post', 'https://foo.bar.com/login', {email, password}).then().catch() } }

But I get an error like this:

Failed to load https://foo.bar.com/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Categories: Software

Extending VueJs bundled Typescript definitions for VueRx

Vuejs - Mon, 2017-09-11 16:41

I'd like to use VueRx in a Typescript project.

VueRx extends the Vue prototype with several methods: https://github.com/vuejs/vue-rx#other-api-methods. Since VueRx does not ship with TS declarations, I would like to roll my own. Unfortunately I'm unable to come up with a way to extend the Vue declarations bundled with VueJs due to the way the declaration is written (classes rather than interfaces). Any suggestions?

Categories: Software

How to pass a data to child component only once during mounting component in vuejs?

Vuejs - Mon, 2017-09-11 16:32

I would like to pass data to child component but do not want to bind it when the data changes in the parent

<parent :val="myval"> <child :initialval="val"></child> </parent>

This code binds my initial value to myval, I just want it to be passed first time and do not want initialval to be reactive to changes of my val.

Can I do it without setting a local variable in mounted() function of child component?

Categories: Software

Laravel VueJs Array's

Vuejs - Mon, 2017-09-11 15:25

I'm using Laravel 5.5 and VueJS for my application.

I have a form on the vue instance which allows the user to enter details of an individual and add them to a visit. When added my method adds the details from the inputs to the array of visitors.

PROBLEM: When I add a visitor to the visitors array and click remove it works great, when I import and click remove on one of the visitors it removes the wrong visitor.

My vue instance (part)

data: { visitor: {}, }

My form

<input v-model="visitor.last" class="input" placeholder="Last Name"> <input v-model="visitor.company" class="input" placeholder="Company"> <input v-model="visitor.email" class="input" placeholder="Email" type="email"> <button class="button is-primary" @click="saveVisitor">Add Visitor</button>

My Method

saveVisitor() { this.visitors.push(this.visitor); this.visitor = {}; },

This all works great and works as it should, I've now added another method for populating the list of Visitors and this is a spreadsheet import which I parse in my Laravel backend and return to my Vue instance.

METHOD FOR SPREADSHEET

submitImport() { const vm = this; var form = new FormData(); form.append('file', document.getElementById('file').files[0]); axios({ method: 'post', url: '/import/visitors', data: form }).then(function(response){ if(response.status === 200){ vm.visitors = response.data; } else { vm.loading = false; } }); },

When going through the spreadsheet I build up a array in the backend:

Laravel Controller (part)

$visitor[] = array( 'first' => $v->FirstName, 'last' => $v->LastName, 'email' => $v->Email, 'company' => $v->Company );

After the function has finished looping through the rows on the spreadsheet my controller returns the array back to the vue instance.

return response($visitor,200);

I accept the array on my Vue Instance and populate the visitors array on my vue instance with the results.

vm.visitors = response.data;

And this works great! my only problem is that when I try to remove one of the visitors from the vm.visitors array it removes the wrong one which I'm guessing is due to the keys.

see my remove method.

removeVisitor(visitor) { console.log(visitor); //this.visitors.splice(visitor,1); },

When I view the console I get the following, please note I've added some from the spreadsheet import and some via the form inputs.

It looks as though the visitors array on my vue instance has two different types of data.

Screenshot of my image

When you click the ... in the top object this does return the name etc but this is different from the 2nd object which contains the data clearly?

Categories: Software

how do I activate a sub menu route from a main menu route - vue-router

Vuejs - Mon, 2017-09-11 15:14

Hi all I need some help with activating a sub menu route from a main menu route - vue-router. I have the following code in my app.js for routing. The children object has a sub-route that I want highlighted when the main menu nav link (transactions) is clicked. In my browser URL I see http://localhost:3000/transactions/transaction_history which tells me that it is going to the destination I want but I have no clue to get the sub-route active from the main nav? Any help will be great.

app.js

const routes = [ { name: 'transactions', path: 'transactions/transaction_history', component: transactions, children: [ { name: 'transaction-history', path: '/transactions/transaction_history', component: transaction_history } ] } ]

In my navigation.vue I have

<li class="u-nav__tab-item pull-left"> <router-link v-bind:class="{ 'u-nav__tab-item--active' : $route.name === 'transactions' }" :to="{ name: 'transactions', path: '/transactions' }" exact>Transactions <div class="u-nav__dropdown-arrow pull-right"></div> </router-link> </li>

And in my transactions.vue template I have this link which is the first-child of the sub menu

<li class="o-pf-list__item o-pf-list__item--border o-pf-list__item--line-height" :class="{ 'u-nav__tab-item--active-border-left' : $route.name === 'transaction-history' }"> <router-link v-bind:class="{ 'u-nav__tab-item--active' : $route.name === 'transaction-history' }" :to="{ name: 'transaction-history', path: '/transactions/transaction_history' }" exact>Transaction History</router-link> </li>

Example of what I want when the main nav is clicked. This is the sub menu first child.

enter image description here

Categories: Software

Vue.js clearing data after if is evaluated

Vuejs - Mon, 2017-09-11 14:42

I am making a multi-step form in Rails 5 with Vue.js. I noticed that when a v-if is re-evaluated, the text in the input field gets cleared out. Is there a way to persist the info through the form steps and through other v-if evaluations?

Here's what my form looks like:

<fieldset class="listing-step" v-if="activeStep === 0"> <h2>Basics</h2> <input type='button' value="Next" name='next' @click="activeStep++" :disabled="activeStep === stepList.length - 1" class="btn btn-secondary" /> <div class="row"> <div class="col"> <div class="form-group"> <strong><%= f.label :name %></strong><br> <%= f.text_field :name, class: 'form-control' %> </div> </div> </div> </fieldset> <fieldset class="listing-step" v-if="activeStep === 1"> <h2>Location</h2> <input type='button' value="Previous" name='prev' @click="activeStep--" :disabled="activeStep === 0" class="btn btn-secondary" /> <input type='button' value="Next" name='next' @click="activeStep++" :disabled="activeStep === stepList.length - 1" class="btn btn-secondary" /> <div class="row"> <div class="col"> <div class="form-check"> <label class="form-check-label"> <input class="form-check-input" type="radio" name="map_search" id="map_search_address" value="address" v-on:click="by_address = true" checked> Set by address </label> </div> <div class="form-check"> <label class="form-check-label"> <input class="form-check-input" type="radio" name="map_search" id="map_search_coords" value="coords" v-on:click="by_address = false"> Set by coordinates </label> </div> </div> </div> <div id="listing-location"> <transition name="fade"> <fieldset id="listing-location-child" name="address" v-if="by_address"> <div class="row"> <div class="col"> <div class="form-group"> <strong><%= f.label :city %></strong><br> <%= f.text_field :city, class: 'form-control', 'v-bind:readonly': '!by_address' %> </div> </div> <div class="col"> <div class="form-group"> <strong><%= f.label :state %></strong><br> <%= f.text_field :state, class: 'form-control', 'v-bind:readonly': '!by_address' %> </div> </div> </div> <div class="row"> <div class="col"> <div class="form-group"> <strong><%= f.label :address %></strong><br> <%= f.text_field :address, class: 'form-control', 'v-bind:readonly': '!by_address' %> </div> </div> </div> </fieldset> </transition> <transition name="fade"> <fieldset id="listing-location-child" name="coords" v-if="!by_address"> <div class="row"> <div class="col"> <div class="form-group"> <strong><%= f.label :lat, 'Latitude' %></strong><br> <%= f.number_field :lat, in: -90.0..90.0, step: :any, class: 'form-control', 'v-bind:readonly': 'by_address' %> </div> </div> <div class="col"> <div class="form-group"> <strong><%= f.label :lng, 'Longitude' %></strong><br> <%= f.number_field :lng, in: -180.0..180.0, step: :any, class: 'form-control', 'v-bind:readonly': 'by_address' %> </div> </div> </div> </fieldset> </transition> </div> </fieldset> <fieldset class="listing-step" v-if="activeStep === 2"> <h2>Amenities</h2> <input type='button' value="Previous" name='prev' @click="activeStep--" :disabled="activeStep === 0" class="btn btn-secondary" /> <input type='button' value="Next" name='next' @click="activeStep++" :disabled="activeStep === stepList.length - 1" class="btn btn-secondary" /> <div class="row"> <div class="col"> <div class="form-group"> <strong>Amenities</strong><br> ... </div> </div> </div> </fieldset> <fieldset class="listing-step" v-if="activeStep === 3"> <h2>Images</h2> <input type='button' value="Previous" name='prev' @click="activeStep--" :disabled="activeStep === 0" class="btn btn-secondary" /> <div class="row"> <div class="col"> <div class="form-group"> <strong>Images</strong><br> ... </div> </div> </div> <div class="row"> <div class="col"> <div class="actions"> <%= f.submit class: 'btn btn-success' %> </div> </div> </div> </fieldset>

and my Vue initialization:

const progress = new Vue({ el: '#vue-listing', data: { activeStep: 0, by_address: true, stepList: [ {id: 0, text: 'Basics'}, {id: 1, text: 'Location'}, {id: 2, text: 'Amenities'}, {id: 3, text: 'Images'} ] } })

Thanks in advance!

Categories: Software

Fetching data from api before render component

Vuejs - Mon, 2017-09-11 14:20

I'm sending 2 api requests before render the page:

const Profile = { template: '#profile', attributes: null, photos: [], data: function () { return {attributes: Profile.attributes, photos: Profile.photos}; }, beforeRouteEnter: function (to, from, next) { function getProfile() { return axios.get('user/get-profile?access-token=1', {responseType: 'json'}); } function getPhotos() { return axios.get('photos?access-token=1', {responseType: 'json'}); } axios.all([getProfile(), getPhotos()]) .then(axios.spread(function (profile, memes) { console.log(profile, memes); next(vm => { vm.setProfile(profile); vm.setPhotos(photos); }) })); }, methods: { setProfile: function (response) { Profile.attributes = response.data; console.log(Profile.attributes); }, setPhotos: function (response) { Profile.photos = response.data; console.log(response); }, } };

The problem is rendering occures before setProfile and setPhotos methods. How to correct render my component?

Categories: Software

Karma unit test Vue.js + Foundation

Vuejs - Mon, 2017-09-11 13:22

I'm attempting to add Foundation for Sites to my first Vue.js project that is setup with the Vue CLI.

The website runs however the Karma+Phantomjs unit test suite is emitting this error:

PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR SyntaxError: Invalid character: '`' at webpack:///~/foundation-sites/js/foundation.util.core.js:24:0 <- index.js:10362

I believe this is related to webpack and

Here's an overview of the code changes I've made...

Main.js

import jQuery from 'jquery' window.jQuery = jQuery window.$ = jQuery import Foundation from 'foundation-sites' window.Foundation = Foundation

Hello.vue

<template> ... </template> <script> export default { name: 'hello', mounted () { this.dropdownMenu = new Foundation.DropdownMenu($('#dropdown-menu'), { // These options can be declarative using the data attributes hoverDelay: 300 }) }, data () { return { msg: 'Welcome to Your Vue.js App' } }, destroyed () { this.dropdownMenu.destroy() } } </script>

test/unit/index.js

import Vue from 'vue' import Foundation from 'foundation-sites' window.Foundation = Foundation // ... auto-generated unit tests
Categories: Software

Vue.js close modal from child component

Vuejs - Mon, 2017-09-11 12:54

I want to close vuejs modal from child component inside this modal. Case:

<modal name="some-modal"> <some-component></some-component> </modal>

Inside SomeComponent i want to close some-modal. Is it good approach ? Can it be done better way ? Please adivse, Regards

Categories: Software

Virtual Box Ubuntu, Laravel backend api, Vue frontend - can't connect Vue to Laravel api url

Vuejs - Mon, 2017-09-11 12:38

I have VirtualBox Machine on windows 10, I have Laravel backend api, and Vue for frontend. Now when I run Vue with npm run dev, it starts my Vue app on localhost port 8080, and my Laravel app is on vue.dev/api/quote (this is for post url)

I am using axios and when in my axios.post put my laravel url, I am getting errors in the browser console.

axios.post('http://vue.dev/api/quote', {content: this.quoteContent}) .then( (response) => console.log(response) ) .catch( (error) => console.log(error) );

I can access on ubuntu laravel url and it works. Cant find where is a problem in vue, because when i hit submit button on vue app, I just keep getting error.

enter image description here

Categories: Software

Vuejs eventbus triggers multiple times due to webpack import outport?

Vuejs - Mon, 2017-09-11 12:30

In a vuejs project I use the vue eventbus like this. Emitting this event:

icontag.addEventListener('click', testFunction, false) function testFunction () { console.log('click1') Events.$emit('click2') }

And receiving it in another module I get as output one click1, but multiple click2's. It looks very much like every time there is some code which requires webpack import/ export it triggers an additional result on the eventbus of the same event..., or something..., since in chrome devtools the related code close to the click2's has code like __WEBPACK_IMPORTED_MODULE_5__util nearby.

Any idea what is going on?

Categories: Software

Custom vue events not working

Vuejs - Mon, 2017-09-11 12:00

I am trying to catch vue.js custom event within one component, but it's not catching. What's the problem?

myEventFunc: function() { this.myEvent = true; }, clickedFunc: function() { this.clicked = true; this.$emit('myevent'); }

JSFiddle Example: https://jsfiddle.net/ucean0rh/1/

Categories: Software

Pages