Software

Vue.js: best practice with managing JS for other components

Vuejs - Tue, 2017-08-15 21:33

I have a simple website set up with Vue.js. I have a component for each page (About us, Contact us, etc). Each component fetches the markup for the page via ajax then injects it using <vue-router>.

So far so good.

My question is: what should I do with all the JS that's only used for specific components? My home page might have ~100 lines of JS just for setting up image sliders, hover events, etc. Once I load the About Us component, all that JS for the home page still exists in the browser but it's no longer relevant. Should I manually be nullifying my variables?

What about this case: User visits the Home page, then the About page, then back to Home. On the 2nd visit of the home page, all my old variables still exist, but aren't necessarily in the correct state anymore. I'll want to move sliders back to slide 1, reset any hovers... basically just reset the page.

I guess I'm asking for a very high level overview on how to best manage the JS for multiple components and how it all ties in with document.ready and window.load callbacks once they've already fired and won't fire again. Thanks.

Categories: Software

How to filter data from each filter value in Vuejs2?

Vuejs - Tue, 2017-08-15 20:33

I am trying to create filters with dynamic parameters for a datatable in vuejs2 . the grid data come from an Api rest in Laravel. I have a computed function which filters data and all filters are in different inputs. I have an object that has the values of the filters. i have the filter in a computed function but i am filtering with conditions. how can i filter for each filter value in each item property?, how can i make my code works for each item in the filters and every property of the data object without write all the conditions?

my data is :

data:function(){ gridFields:{gridfilters:{fname:'',fdescription:''}}, gridApiData: [ { "id": 10057, "name": "10053", "description": "10053" }, { "id": 10058, "name": "10054", "description": "10054" }, { "id": 10059, "name": "10055", "description": "10055" } ] }

The fname and fdescription are the values of the input filters.

my computed function is :

computed:{ //I need to filter the data array with all the filters from the filter object gridFields.gridfilter dataList:function(){ var vm = this; return this.gridApiData.filter(function (item) { if(vm.gridFields.gridfilters.fname && !vm.gridFields.gridfilters.fdescription){ return (item.name.toLowerCase().indexOf(vm.gridFields.gridfilters.fname.toLowerCase()) !== -1); } if(!vm.gridFields.gridfilters.fname && vm.gridFields.gridfilters.fdescription){ return (item.description.toLowerCase().indexOf(vm.gridFields.gridfilters.fdescription.toLowerCase()) !== -1); } if(vm.gridFields.gridfilters.fname && vm.gridFields.gridfilters.fdescription){ return ((item.name.toLowerCase().indexOf(vm.gridFields.gridfilters.fname.toLowerCase()) !== -1) && (item.description.toLowerCase().indexOf(vm.gridFields.gridfilters.fdescription.toLowerCase()) !== -1)); } return item;}); } },

thank you for all the suggestions.

Categories: Software

How to make a 'most common time of day' chart javascript?

Vuejs - Tue, 2017-08-15 20:27

enter image description here

Google Analytics has a great chart in the section "When do your users visit?"

The title is "Users by Time of Day"

The X Axis (bottom of chart) shows "Sun Mon Tues Wed Thurs Fri Sat"

The Y Axis (right side of chart) shows "12am 2am 4am 6am ..."

In the chart are boxes colored dark blue for busy times, lighter blue for less busy times.

Hovering shows the number the box represents

I cannot find a chart anywhere to do this, unfortunately not even Google Charts offers a chart like this

I want to visually represent the most common times users play an online game, that way it will be clearly represent that "9pm on a Sunday" is the best time to play for example.

Anyone know of a javascript library to make a chart like this??

Categories: Software

Vue not setting <select> value by v-model in IE

Vuejs - Tue, 2017-08-15 20:08

This seems to work in Chrome, but not IE. Do you have any ideas why?

<select v-model="selected"> <option v-for="option in options" :value="option">{{ option.foo }}</option> </select> var data = [{ foo: 1 }, { foo: 2 }] var demo = new Vue({ el: '#demo', data: { selected: null, options: data }, mounted: function() { this.selected = data[1] } })

http://jsfiddle.net/yMv7y/3267/

Categories: Software

Invalid expression passing props in vue.js template - IE11

Vuejs - Tue, 2017-08-15 19:11

I'm new to vue.js and I'm trying to create a vue component.

Vue.component('sales-report', { data: function(){ return {products: products, seasons: seasons}} template: '<course-details-menu :dropdown-data="{ products, outlineClassifications, seasons, years }"></course-details-menu>' });

This is a simplified example of my app, and it works in Chrome, but in IE, I get this error from vue:

Error compiling template:: - invalid expression: :dropdown-data="{ products, seasons }" found in --->

Categories: Software

VueJS - When input value change, display in another div

Vuejs - Tue, 2017-08-15 18:50

I would like, to capture the value of my input and display on another div.

Look my code :

If you look the code, I save the value in function msgFunc, and after that I would apply this result in my variable msg, but I don't understand.

Thanks !

export default { data () { return { msg: '' } }, computed: { msgFunc: () => { return this.value } } } .flex { display: flex; flex-flow: row wrap; justify-content: center; align-items: center; height: 90%; } .input-container { width: 410px; background-color: #fff; padding: 2px 15px 20px 15px; box-shadow: 0 16px 24px 2px rgba(0,0,0,0.14), 0 6px 30px 5px rgba(0,0,0,0.12), 0 8px 10px -5px rgba(0,0,0,0.3); transition: transform .1s ease-in-out; } .input-container input { margin-top: 10px; width: 100%; border-bottom: 1px solid #25A3FF; padding: 10px 0; font-size: 16px; color: #929292; } input:focus { outline: none; } <div class="flex"> <section class="input-container"> <input type="text" v-model="msg" @change="msgFunc" placeholder="Type your HEX color"> <h3>{{msg}}</h3> </section> </div>

Categories: Software

Vue js toggle class of individual element

Vuejs - Tue, 2017-08-15 18:19

While there are many examples of toggling classes in Vuejs, I am yet to find one that toggles a class narrowing down the scope of the element. If I define a global variable like this:

data { toggle: false }

I will run into a problem when I have an element, like this navigation bar:

<ul class="menu"> <li class="has-dropdown" v-bind:class="{ 'is-open': toggle }" @click="toggle = !toggle"> Foo <ul class="dropdown"> <li>Dropdown Item 1</li> <li>Dropdown Item 2</li> </ul> </li> <li class="has-dropdown" v-bind:class="{ 'is-open': toggle }" @click="toggle = !toggle"> Bar <ul class="dropdown"> <li>Dropdown Item 1</li> <li>Dropdown Item 2</li> </ul> </li> </ul>

See what happens here? If I click in one of these two elements, both are going to toggle the class, because it's changing a global variable. Now, how would I toggle the class of only the element that is clicked?

Categories: Software

How to make a condition to add/remove data param in Vue?

Vuejs - Tue, 2017-08-15 16:49

e.g.:

<div :data-some="someData ? okay : bad" :data-someother="someOtherData ? okay : bad"> </div>

I want not to specify any data-params if there's "bad" in the result.

How can I do that?

Categories: Software

Add row to table with vue.js in a v-for tag

Vuejs - Tue, 2017-08-15 16:38

I need to add rows in table #dynamic but table static shouldn't be affected. If i hit button with the code below, of cause both tables will be updated, because they have the same v-for. And if I put a v-for in a v-for my datas wont be fetched. I can't figured it out how to "unique" the first table.

vue/html <template> <table id="dynamic"> <tr v-for="rows in list"> <td>Content of row {{ rows.item1 }}</td> <td>Content of row {{ rows.item2 }}</td> </tr> </table> <div @click="block = !block">click</div> <table id="static"> <tr v-for="rows in list"> <td>Content of row: {{ rows.item3 }}</td> <td>Content of row: {{ rows.item4 }}</td> </tr> </table> </template> js export default { data: function () { return { list: [], }; }, props: ['channelId'], mounted() { }, created() { this.fetchChannel(this.channelId); }, methods: { fetchChannel: function (channelId) { $.getJSON('/api/channel/' + channelId, function (data) { this.list = data; }.bind(this)); }, } }

I found some examples for help like this codepen or fiddle but I am not successful with it.

Hope somebody can help me in my case.

Categories: Software

Vuejs display a value within an object returned by a method

Vuejs - Tue, 2017-08-15 16:25

I want to display the 'name' value only, within the object returned from the method.

  • What is currently displayed is: [ { "city": "Ottawa", "name": "Senators", "province": "Ontario", ".key": "-Kp00XARET2EDFRZVMks" } ]

  • I want displayed is "Senators".

Here's snippets of my code:

... in the template <td>{{props.item.away}} {{ teamDetail(props.item.away) }}</td> ... in the script methods: { teamDetail(inpt) { return this.teams.filter((team) => { return team['.key'] == inpt; }) },

props.item.away is the .key sent to teamDetail to retrieve the object for a specific team, the object returned in this case is [ { "city": "Ottawa", "name": "Senators", "province": "Ontario", ".key": "-Kp00XARET2EDFRZVMks" } ]

to display the 'name' only, I tried within the template {{ teamDetail(props.item.away).name }} and within the filter in the method

Categories: Software

Can't load images from assets folder in nested components (Vue.js 2.0 / Webpack)

Vuejs - Tue, 2017-08-15 15:59

I'm new to webpack and Vue.js. I'm facing issues when trying to load images/videos in my nested components, it gives me "not found" error. I have project structure like that: Project structure image

Let's say in Signup.Vue I want to load an image from the assets folder, how can I do that? Because ".../assets/my-img.jpg" didn't work out, "assets/my-img.jpg" neither. In css I figured out that using require with "~" works (ex. '~assets/my-img.jpg" ). I don't undestand how paths work.

Placing my images in the same component's folder would be an option, but I want to use the main assets folder where I can fetch media from.

Using: webpack 2.7.0 / vue 2.0

Thank you in advance

Categories: Software

Vue instance not mounting on instantiation

Vuejs - Tue, 2017-08-15 15:42

I am using vue-loader in webpack and have a dialog.vue file with script, style and template.

When I import the file to another file and call new Vue(dialog) I get a instance. But if I call .$mount() on it (to mount it off DOM) I get a error:

[Vue warn]: Failed to mount component: template or render function not defined.

When I do console.log(dialog.render) I se the function there, when I do console.log(instance.render) its undefined.

If I instanciate it without calling .$mount() the instance has no .$el property, its undefined...

What am I missing? how else can I import a .vue file to another and call new Vue() to instanciate it and then mount it so I have a .$el element from the instance?

Categories: Software

How to give access to page in Vue.js only if a user is logged in / localStorage exists?

Vuejs - Tue, 2017-08-15 15:03

I currently have a simple Vue.js application, I am using vue-router like this. index.html

<p> <router-link to="/" exact> Home </router-link> <router-link to="/about"> About </router-link> <router-link to="/contact"> Contact </router-link> <router-link to="/login"> Login </router-link> <router-link to="/register"> Register </router-link> </p> <router-view></router-view>

And I have this in my /routes.js

import VueRouter from 'vue-router'; let routes = [ { path: '/', component: require('./components/Home.vue') }, { path: '/about', component: require('./components/About.vue') }, { path: '/login', component: require('./components/Login.vue') }, { path: '/register', component: require('./components/Register.vue') } ]; export default new VueRouter({ mode: 'history', routes });

I have index.js file which initialized the app, I think I should do something within my created(){} module but I am not sure how it is done.

I can set/unset sessions, all I need to know is how to give access to a page only if this session exists.

Categories: Software

How to keep the status on "friends" in my vue file

Vuejs - Tue, 2017-08-15 14:07

I have a Friend.vue file where different states are being called and executed, so when users are not friends it displays icon -a- if request was send it displays icon -b- and when users are friends it should display icon -c- (chat icon so the users can chat)

but after the request is accepted icon -a-(send request) is displayed again because the status is -reset- to '0' but i can't figure out why.

my Friend.vue file

<template> <div> <p class="text-center" v-if="loading"> Laden... </p> <p class="text-center" v-if="!loading"> <a v-if="status == 0" @click="add_friend"><span title="Vriendschapsverzoek" class="add-friend"></span> </a> <a href=""><span title="Vriendschap bevestigen" class="accept-friend" v- if="status == 'pending'" @click="accept_friend"></span></a> <a href=""><span title="wachten op een reactie" class="pending" v- if="status == 'waiting'"></span></a> <a href=""><span v-if="status == 'friends'" title="Chatten" class="chat"> </span></a> </p> </div> </template> <script> export default { mounted() { this.$http.get('/check_relationship_status/' + this.profile_user_id) .then((resp) => { console.log(resp) this.status = resp.body.status this.loading = false }) }, props: ['profile_user_id'], data() { return { status: '', loading: true } }, methods: { add_friend() { this.loading = true this.$http.get('/add_friend/' + this.profile_user_id) .then((r) => { if (r.body == 1) this.status = 'waiting' this.loading = false }) }, accept_friend() { this.loading = true this.$http.get('/accept_friend/' + this.profile_user_id) .then((r) => { if (r.body == 1) this.status = 'friends' this.loading = false }) } }

}

the (relevant)functions in my controller

public function check_relationship_status($id){ if (Auth::user()->is_friends_with($id) === 1) { return [ "status" => "friends" ]; } if(Auth::user()->has_pending_friend_request_from($id)) { return [ "status" => "pending" ]; } if(Auth::user()->has_pending_friend_request_sent_to($id)) { return [ "status" => "waiting" ]; } return [ "status" => 0 ]; } public function add_friend($id) { return Auth::user()->add_friend($id); } public function accept_friend($id) { return Auth::user()->accept_friend($id); }

and the "button" that should display these icons

<friend :profile_user_id="{{ $user->id }}"></friend>

If I should add any more code to make it more clear or any other suggestion please do tell, this is my first laravel site, plus the first time I'm trying out Vue.js so please be kind to my beginners mistakes. thank you

Categories: Software

Vue.js 2, Using custom component tag names in css?

Vuejs - Tue, 2017-08-15 11:50
<template> <header> <hamburger></hamburger> <app-title></app-title> <lives></lives> </header> </template> <script> export default { name: 'Titlebar', data() { return { } } } </script> <style lang="scss" scoped> @import "../styles/variables"; header { padding: $padding-titlebar; position: relative; } lives { position: absolute; right: 2.5vh; } </style>

Is it possible to use component tags like any regular HTML tag for styling purposes like I've written down there in lives { }?
I see that that writing <lives class="lives"> and using .lives { } in css works but that seems kinda redundant, would rather like to ommit adding aditional classes if it's possible to just use component tag.
I understand that Vue compiles <lives> into HTML code and that there is no "lives" tag for css to use after it's compiled, but still wondering.

Categories: Software

Hide input fields by form name - Vuejs

Vuejs - Tue, 2017-08-15 11:29

I have a vuejs form component that has about 5 input fields for example.

But I need to separate the form component into 2 forms that take different user input.

Form 1 has

Name
Surname
Email

with a form name attribute value or form_1

Form 2 has

Username
Password

with a form name attribute value or form_2

The code:

created: function (formNameAttribute, inputNameAttribute) { var getForms = document.getElementsByTagName('form'); var inputElement = document.querySelectorAll('input'); for (var i = 0; i < getForms.length; i++) { formNameAttribute = getForms[i].name; switch (getForms[i].name) { case 'Account Details': console.log('Form Name: ', getForms[i].name); break; case 'Account Login': console.log('Form Name: ', getForms[i].name); break; default: } for (var j = i; j < inputElement.length; j++) { inputNameAttribute = inputElement[j].name; console.log('Input name attribute: ', inputNameAttribute); } }

}

How can I tell the form component to only display the fields it needs for form_1 and form_2

external link to code: Form Component

Categories: Software

what does a red dot in VS code mean

Vuejs - Tue, 2017-08-15 11:25

So I'm learning vue.js and vsCode is giving me this red dot on my code, the code is running perfectly fine and other editors such as atom is giving me no errors. What is that red dot for?

Categories: Software

Using v-bind:class with dynamic variable

Vuejs - Tue, 2017-08-15 11:08

I have a variable in my component data, which I can access in my element with;

<input :id="guid">

I want to use this guid with v-bind:class; something like this:

v-bind:class="{ 'has-warnings': warnings[guid]['name'] }" >

I also tried this but no chance:

v-bind:class="{ 'has-warnings': warnings[{{guid}}]['name'] }" >

Is there a way to do it?

Categories: Software

Mapping array in Vue JS

Vuejs - Tue, 2017-08-15 10:59

I'm developing a small application in VueJS 2.0 where I'm having a data set something like this:

{"data": [ { "id":8, "salutation":"Mr", "first_name":"Madhu", "last_name":"Kela", "number":"2343253455", "mobile":"3252345435", "email":"madhu@reliancemf.com", "alt_email":null, "address":"Mumbai BKC", "city":"Mumbai", "state":null, "country":"India", "profile":null, "sectors_interested":"[\"Insurance\",\"Infrastructure\",\"Information Technology\",\"hevy machines\",\"Healtcare\"]", "companies_interested":"[4]", "interactions_count":11, "client_interactions_count":0, "company":[ { "id":7, "name":"Reliance MF", "address":"Mumbai BKC", "city":"Mumbai", "state":null, "country":"India", "type":"Investor", "sub_type":"Mutual Fund", "is_client":0, "pivot":{ "contact_id":8, "company_id":7, "created_at":"2017-07-01 17:07:08", "updated_at":"2017-07-01 17:07:08" } } ] }, { "id":7, "salutation":"Ms", "first_name":"XYZ", "last_name":"ABC", "number":"1847171087", "mobile":"8327523057", "email":"skbkjgerbra@dabflvdjf.com", "alt_email":null, "address":"Mumbai", "city":"Mumbai", "state":null, "country":"India", "profile":null, "sectors_interested":"[\"Insurance\",\"Information Technology\",\"Infrastructure\",\"hevy machines\"]", "companies_interested":"[6,4]", "interactions_count":8, "client_interactions_count":0, "company":[ { "id":3, "name":"Franklin Fun", "address":"Mumbai", "city":"Mumbai", "state":null, "country":"India", "type":"Investor", "sub_type":"Mutual Fund", "is_client":0, "pivot":{ "contact_id":7, "company_id":3, "created_at":"2017-07-01 16:59:41", "updated_at":"2017-07-01 16:59:41" } } ] } ] }

I want map these values something like this:

return this.model.map(d => ({ name: d.first_name + ' ' +d.last_name, company: d.company[0].name, email: d.email, mobile: d.mobile, profile: d.profile, count: d.interactions_count ? d.interactions_count : d.client_interactions_count }))

Also as you see in the code I want to place interactions_count by comparing i.e. if interactions_count is 0 I want to map with client_interactions_count, I'm unable to get company name from the first array parameter, whatever it comes by response. Help me out in this. Thanks.

Categories: Software

Laravel and axios clear Form after submit

Vuejs - Tue, 2017-08-15 10:14

In my Laravel app i'm submitting a form with vue and axios. After the submit i want to clear the input field in the form, but it wont work.

HTML:

<form method="post" enctype="multipart/form-data" v-on:submit.prevent="addPost"> <textarea id="post_area" v-model="content"></textarea> ..... </form>

JS:

const app = new Vue({ el: '#app', data: { content: '', posts: [] }, ...... .then(function (response) { if(response.status===200) { //reload posts app.posts = response.data; this.content = ''; } })

It just wont clear out the input field.

Categories: Software

Pages