Vuejs

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

Vue.js two-way data binding for forms - how to approach cancelling edits?

Wed, 2017-08-09 22:32

I'm creating a CMS with Vue.js for studying purposes.

I have a list of posts that load into the selectedPost object when I click the title. This selectedPost object is bound to a form, an "edit" form. Now when I start editing the form, all changes sync to the selectedPost (and the list of posts) in real time, which is pretty neat, but I would like to have the regular form, in which the user has to click 'submit' to sync changes.

How to do that using vue? Can a bound object sync only on command?

Categories: Software

Only load data when component is in view?

Wed, 2017-08-09 21:41

Im having some problems with my data getting loaded even if the component is not in the current view I have a list with 500 elements, which is why each component should only load it's data when scrolled to the element is the list...

  • Im using this mixin:-

https://github.com/BKWLD/vue-in-viewport-mixin When the component is mounted, then I have a watcher to see if the current component is in the view, however, doesn't quite seem to work quite as I hoped, or maybe im using it wrong.

Either way, no matter what it calls my function this.loadDataToSystem(); even if the component is not in the current view. What I want is to only call the function when I've scrolled to the component...

The component looks is this:-

<template> <div> <template v-if="elementIsVisible"> <div class="grid-tile__content" :class="{ 'is-alarm': system.pending_events === 'alarm', 'is-acknowledged-alarm': system.pending_events === 'alarm-acked', 'is-warning': system.pending_events === 'warning', 'is-info': system.pending_events === 'event', 'is-offline': system.status === 'Offline', 'is-online': system.status === 'Online'}"> <h2 class="grid-tile__system-name"> <span>{{system.name}}</span> </h2> <p class="grid-tile__unit-name">System Pressure</p> <div class="grid-tile__content__loading" v-if="loading"> <loading></loading> </div> <div v-else> <div class="grid-tile__footer"> <div class="grid-tile__chart-info"> <span class="grid-tile__chart-number"> <template v-if="system.last_value !== ''">{{system.last_value}}</template> <template v-else>N/A</template> </span> <span class="grid-tile__chart-unit"> <template v-if="system.unit.length > 0"> {{system.unit}} </template> <template v-else> N/A </template> </span> <!--span class="grid-tile__chart-prev-number">3.34%</span--> </div> <div class="grid-tile__notification"> <span class="grid-tile__notification-circle"></span> <span>02.aug / 09:34am</span> </div> </div> </div> </div> </template> </div> </template> <script> import SystemService from '../../../../Api/Systems'; import Loading from '../../../../Icons/AltenateLoader.vue'; import inViewport from 'vue-in-viewport-mixin'; export default { props: ['systemData', 'startDate', 'endDate', 'frequency'], mixins: [ inViewport ], watch: { 'inViewport.now': function(visible) { if(visible) { this.loadDataToSystem(); //This should only be triggered if the user has scrolled to the component- So if the component is in the current view this.elementIsVisible = true; } else { this.elementIsVisible = false; } } }, data() { return { endpointConf: { start: this.startDate, end: this.endDate, frequency: this.frequency }, system: { status: '', pending_events: '', name: this.systemData.name, last_online: '', unit:'', y_max_value: '', y_min_value: '', last_value: '' }, data: this.systemData, loading: true, elementIsVisible: false } }, components: { Loading }, methods: { loadDataToSystem() { SystemService.getSystem(this.data.id).then(response => { if(response.status === 200) { console.log("load data"); } }).catch((error) => { console.log("Fejl:" + error); }); } }, created() { } } </script>
Categories: Software

Which event does Vue.js listen to when triggering data binding?

Wed, 2017-08-09 21:30

I have a textbox bound to a Vue.js object, like this:

<textarea id="post-content-textarea" v-model="selectedPost.content" v-bind:value="selectedPost.content"></textarea>

I want to programatically change the content of this textarea with jquery, like this:

$('#post-content-textarea').val("New Value");

But it is not updating the bound js object (only if I manually type on the textarea), so I tried triggering the "change" and "input" events, without success. My question: Which event should I trigger to make it update the object?

Categories: Software

how to have Vuex mapState with computed properties in vuejs

Wed, 2017-08-09 21:24

I'm trying to learn Vuex and tried adding the mapState with local computed property in my Vuejs 2.0 application on top of Laravel 5.4, now while adding so I'm getting following error:

Syntax Error: Unexpected token, expected , (379:32) 377 | }, 378 | mapState({ > 379 | contactStore: state => state.contactStore | ^ 380 | }) 381 | } 382 | }

Here is my component:

<template> <div class="row"> <div class="table-responsive"> <table class="table table-striped"> <tbody> <tr> <th class="text-left">Contact Name</th> <th class="text-left">Company Name</th> <th class="text-left">City</th> <th class="text-left">Email</th> <th class="text-left">Mobile</th> <th class="text-left">Type</th> <th class="text-left">SubType</th> <th class="text-left">Profile</th> </tr> <tr v-for="(item, index) in tableFilter"> <td class="text-left"><a @click="showModal(item)" data-toggle="modal" data-target="#showContactModal">{{ item.first_name+' '+item.last_name }}</a></td> <td class="text-left">{{ item.company.name }}</td> <td class="text-left">{{ item.city }}</td> <td class="text-left">{{ item.email }}</td> <td class="text-left">{{ item.mobile }}</td> <td class="text-left"><span class="badge badge-info">{{ item.company.type }}</span></td> <td class="text-left"><span class="badge badge-info">{{ item.company.sub_type }}</span></td> <td class="text-left"><span class="badge badge-info">{{ item.profile }}</span></td> </tr> </tbody> </table> </div> </div> </template> <script> import {mapState} from 'vuex' export default { data(){ return { id: '', search: '', model: [] } }, computed: { tableFilter: function () { const searchTerm = this.search.toLowerCase(); if(this.model) { return this.model.filter((item) => (item.first_name.toLowerCase().includes(searchTerm) || (item.last_name !==null && item.last_name.toLowerCase().includes(searchTerm)) || (item.company.name !==null && item.company.name.toLowerCase().includes(searchTerm)) ); } }, mapState({ contactStore: state => state.contactStore }) } } </script>

I'm trying to replace table filter computed property with the current contact_list state, how can I achieve this or I'm doing some mistake, even if I do ...mapState({}) it is showing me same type of error:

Syntax Error: Unexpected token (378:8) 376 | } 377 | }, > 378 | ...mapState({ | ^ 379 | contactStore: state => state.contactStore 380 | }) 381 | }

what can be done guide me. Thanks

Categories: Software

Vue.js 2-way data bind only working one way

Wed, 2017-08-09 21:22

I have the following element:

<input type="text" v-model="selectedPost.title" v-bind:value="selectedPost.title">

and I have the following Vue.js app:

var vueapp = new Vue({ el: '#app', data: { selectedPost: {} } });

When I type something on the input, the Vue model is updated, I can see it unning this on my browser console:

vueapp.$data.selectedPost.title

Returns the value typed in the textbox. All good.

But.. when I do this:

vueapp.$data.selectedPost.title = "changed";

The textbox does not update with the assigned value.

Why? How to make it work?

Categories: Software

Change default font in vuetify

Wed, 2017-08-09 21:12

I can't figure out how to change the default font in vuetify. I've been looking for the right variable within ./node_modules/vuetify, but I can't locate it.

I'd ideally not make any changes in the module, but would rather override such variables from outside the module.

Categories: Software

vue-material form POST set

Wed, 2017-08-09 20:32

I would like to make a login page with vue-material. I got the form base from here. There is a laravel 5.4 on the server side.

The html part:

<div id="app"> <md-layout md-tag="form" novalidate @submit.stop.prevent="submit" md-align="center"> <md-layout md-tag="md-card" md-column md-flex="30" md-flex-medium="40" md-flex-small="60" md-flex-xsmall="90" class="md-primary"> <md-card-header> <div class="md-title">Login</div> </md-card-header> <md-card-content> <md-input-container> <md-icon>person</md-icon> <label>Email</label> <md-input email required v-model="email" /> </md-input-container> <md-input-container md-has-password> <md-icon>lock</md-icon> <label>Password</label> <md-input type="password" required v-model="password" /> </md-input-container> </md-card-content> <md-card-actions> <md-button type="submit">Login</md-button> </md-card-actions> </md-layout> </md-layout> </div>

My questions;

  1. How can I set that form use POST and not GET?

  2. How can I set that input fields values should be send?

Thanks for the answers in advance!

Categories: Software

How to use vue js with sails js

Wed, 2017-08-09 19:45

I want to use vue.js as frontend for sails.js and run both client vue.js and server sails.js seperately so that i can get maximum functionality,can someone explain how can i configure to make communication happen between both without any additional package.

Categories: Software

Generating one string out of 3 input fields

Wed, 2017-08-09 19:24

I have 3 input fields (firstname, midname, lastname) that I have created using v-for for each client. Every time client name changes, I want to generate an updated version of the name in an object as a string.

<input :data-index="index" data-field="first-name" @keyup="nameUpdated"> <input :data-index="index" data-field="middle-name" @keyup="nameUpdated"> <input :data-index="index" data-field="last-name" @keyup="nameUpdated">

This is the method I though of, where index is the client count. But then I thought that is not the right way to achieve it. How I thought about it was on nameUpdated function, store client firstname, midname and lastname as an object and then reorganize it like:

client[1][first-name]' + ' ' + client[1][middle-name]' + ' ' + client[1][last-name]'

What is the right way of achieving a task like this?

Categories: Software

component option "computed" should be an object

Wed, 2017-08-09 18:58

I am getting this error in Vue v2.4.1. I am not understanding what does that mean actually. My code looks like this and the warning I am getting is [Vue warn]: component option "computed" should be an object.

export default { data() { return { bookings: [], games: [], slots: [], startTime: { time: moment().format("YYYY-MM-DD") } }; }, components: { 'date-picker': myDatepicker, 'reserved' : Reserved }, ready() { this.prepareComponent(); }, mounted() { this.prepareComponent(); }, methods: { prepareComponent() { this.getGames(); this.getSlots(); this.getBookings(this.startTime.time); }, onDateChange(){ }, formatSlot(slot){ }, getGames(){ } }, getSlots() { }, getBookings(date){ }, isReserved(gameId,slotId){ }, getReservedBooking(gameId,slotId){ }, isPastTime(time, date){ }, getUrl(date,slot_id,game_id){ } } }
Categories: Software

Navigation Tabs is not displaying correctly Vuejs

Wed, 2017-08-09 18:35

I'm using Tabs from Bulma and I learnt how to use the Tabs from Laracast. However, I have a problem which is, I'm able to route correctly as shown in the URL but the tab 'isActive', is not displaying correctly.

Here is the example: enter image description here

index.js (Routing)

{ path: '/user', name: 'User', component: User, children: [{ path: 'Staff', name: 'Staff', component: Staff }, { path: 'ResidentDeveloper', name: 'ResidentDeveloper', component: ResidentDeveloper } ] }

User.vue (only picking out what I think is important)

<tabs> <!--Staff Tab--> <tab name="Staff" :selected="true"> <router-view></router-view> </tab> <!--Resident Developer Tab--> <tab name="Resident Developer"> <router-view></router-view> </tab> </tabs> ... computed: { href () { return '' + this.name.toLowerCase().replace(/\s+/g, '') } }

Tabs.vue (only picking out what I think is important)

... <div class="tabs"> <ul> <li v-for="tab in tabs" :key="tab.name" :class=" { 'is-active': tab.isActive }"> <a :href="tab.href" @click="selectTab(tab)">{{ tab.name }}</a> </li> </ul> </div> ...

Tab.vue (only picking out what I think is important)

... computed: { href () { return '' + this.name.toLowerCase().replace(/\s+/g, '') } } ...

Appreciate your help! Thank you!

Categories: Software

Vue Data not getting updated

Wed, 2017-08-09 17:32

I've the following on the mounted hook in my vue app.

let vm = this; $("button[name='daterange']") .daterangepicker({ ranges: vm.presets, opens: 'left', format: 'YYYY-MM-DD', startDate: startDateValue, endDate: endDateValue }, function(start, end, label) { // cb for when dates are picked let filter = vm.$options.filters.date; vm.range = { start: start, end: end }; console.log(vm.range); vm.$root.$emit('date.change', vm.range); });

and the data is as follows:

data: function() { return { currentRange: 'Last 7 Days', presets: {}, range: {}, } },

For some reason, the watcher for range is not getting executed and I can't see the updated value in vue-dev-tool as well. But when I console log the value of range, it has the right data. This is the reason why I put the emit right below it. Can anyone help me find why the reactivity is not working here?

Categories: Software

Remove error bag in a specific field in Vee Validate

Wed, 2017-08-09 17:16

I have this script where it manually adds an error message in a specific field after I post a form via api

this.errors.add('registration-form.shipping_vmoney_email_address',response.data.message);

This is my HTML:

<input autocomplete="new-email" nofill v-model="shipping_vmoney_email_address" name="shipping_vmoney_email_address" v-validate="'required|email'" :class="{'input': true, 'is-danger': errors.has('registration-form.shipping_vmoney_email_address')}" type="text"> <span v-show="errors.has('registration-form.shipping_vmoney_email_address')" class="help is-danger has-text-left">{{ errors.first('registration-form.shipping_vmoney_email_address') }}</span>

My problem here is the error that I added via this.errors.add, when I type in the email address field the error doesn't remove, is there a way to remove the error of the email address field while i am typing?

Categories: Software

VueJs - How to access DOM property of an element from $refs

Wed, 2017-08-09 17:07

I have an element

<tbody ref="tbody"> <tr class="row" :ref="userIndex" v-for="(userData, uid, userIndex) in users" :key="uid">

in my template. I need to access/edit the DOM property like scrollTop, verticalOffset of <tr> element. How can I achieve this?

I have tried to access using this.$refs[userIndex][0].$el but its not working. I can see all the properties in the console but I am unable to access them. However this.$refs.tbody.scrollTop works. Below is the snap showing console.log(this.$refs)enter image description here

Categories: Software

Inject Vue 'moustache' brackets into HTML element

Wed, 2017-08-09 16:44

I'm learning Vue JS and love it so far. I've got one issue I'm finding difficult to get any ideas on. Is it possible to dynamically 'inject' the moustache brackets (can't find the actual name for these i.e. {{ fooBar }}) into a HTML element? Specific example...

<!-- {{ tweet }} TO BE INJECTED BELOW --> <textarea cols="60" rows="4"></textarea>

I want to inject {{ tweet }} into a textarea element. This is because in my real-world example I can't access and modify the textarea HTML itself. I've tried using jQuery .val() to inject {{ tweet }}, which it does but as plain text. This CodePen will help explain the situation.

If this simply can't be done, are there any alternatives I could look at to dynamically bind the inaccessible textarea?

Categories: Software

Dynamically change the type a chart.js chart in vuejs

Wed, 2017-08-09 16:31

I am using chart.js in a vue application i have four charts declared each for each type of chart. Heres an example of one :

startDoughnut: function (canvas, type) { // init chart.js var ctx = document.getElementById("myDoughnut"); var myDoughnut = this.doughnutChart = new Chart(ctx, { type: 'doughnut', data: { labels: [ 'F0911', 'F0901', 'F0902', 'F0903', 'F0982' ], datasets: [{ data: [300, 50, 100, 60, 25], backgroundColor: [ 'rgba(255, 99, 132, 0.6)', 'rgba(54, 162, 235, 0.6)', 'rgba(255, 206, 86, 0.6)', 'rgba(75, 192, 192, 0.6)', 'rgba(153, 102, 255, 0.6)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 2, hoverBackgroundColor: [ '#FF6384', '#36A2EB', '#FFCE56', '#000066', '#660066' ] }] }, options: { responsive: true, defaultFontColor: '#ffffff', } }) }

I am then using jquery to change between separate divs that hold the canvases and destroy the chart based on a variable I pass in to destroy the chart based on which one is showing then start the next chart and switch the canvas. There is a few bugs like it only works certain times when i click it i am just wondering if there an easy way to do it. Here is one of the jquery functions i have to load a new chart.

$("#buttonPolar").click(function () { if (self.chartType == "doughnut") { $("#doughnut").fadeOut(400); self.doughnutChart.destroy(); } else if (self.chartType == "line") { $("#line").fadeOut(400); self.lineChart.destroy(); } else { $("#bar").fadeOut(400); self.barChart.destroy(); } self.startPolar(self.$refs.canvas, 'polar'); self.chartType="polar"; console.log(self.polarChart); console.log(self.chartType); $("#polar").fadeIn(400); });

Any help would be appreciated.

Categories: Software

Vuejs methods not firing

Wed, 2017-08-09 16:27

When i call a vuejs function from jquery selector it is not firing. I have integrate d3-dagre chart in vue component. when i set a click action for the nodes it is not firing the vuejs methods. In the below getJobid() is not firing. Find the below vue component code and also error in the end.

Vue component:

export default { name: 'dagView', created () { console.log('test2') }, mounted () { var g = new dagreD3.graphlib.Graph().setGraph({}) // Create the renderer var render = new dagreD3.render() // Set up an SVG group so that we can translate the final graph. var svg = d3.select("svg"), inner = svg.append("g") // Run the renderer. This is what draws the final graph. render(inner, g) inner.selectAll("g.node") .on("click", function(v) { console.log("Nodes --> "+ v + " -- "+ g.node(v).label) this.nodeId = g.node(v).label console.log("Node id -- "+ this.nodeId) this.getJobid() }) }, methods: { getJobid: function() { console.log('Received NodeId') } } }

Error:

Uncaught TypeError: this.getJobid is not a function at SVGGElement.eval (DAG.vue?2ccc:180) at SVGGElement.__onclick (d3.v3.min.js:1)
Categories: Software

Add components to Vue instance after instance is created

Wed, 2017-08-09 16:27

If you've created a VueJS instance like this...

var app = new Vue({ el: '#app', components: {...} })

Is it possible to add components to this instance it's instantiated?

The reason I ask is that we have a multi-page app which stares a template. We want the instantiation of the Vue app to be in the shared template code but we want each page to use different components so for example the code on the contact page would be split between two files...

Master.js Contact.js

The contact.js file would need to tell the main app that it wanted to use the conract-form component, but that component is not used on other pages so we don't want to add it to the initial app declaration in the master.js

Any help would really be appreciated.

Categories: Software

Two functions called in v-on:click. Wait one to finish before launching the other?

Wed, 2017-08-09 16:18

I have this div :

[ ... ] <div class="item parent-track" v-on:click="expandTrack(jsonObject.tracks.indexOf(track));setGrey();"> [ ... ] </div> [ ... ]

The method expandTrack creates dynamically new items inside the div and I want to launch the method setGrey (which applies to all the template) after the end of rendering.

It seems that this is not what's happening. expandTrack launches but setGrey is not applying to the items which has been created.

Categories: Software

Multiple instances of a vue.js component and a hidden input file

Wed, 2017-08-09 14:26

I am experiencing a weird behavior using Vue.js 2.

I have a component that I reference twice in a single html page. This component contains an input file control called attachment_file. I hide it using the Bootstrap class hidden and I open the file selection using another button. When a file is selected, I put in a variable called attachment_filename a certain string just like so:

<template> <div> <button @click="selectAttachement"><span class='glyphicon glyphicon-upload'></span></button> <input id="attachment_file" type="file" class="hidden" @change="attachmentSelected"> {{attachment_filename}} </div> </template> <script> export default { data () { return: { attachment_filename: null, } }, methods: { selectAttachement () { $('#attachment_file').click(); }, attachmentSelected () { this.attachment_filename = 'some file here'; }, } } </script>

Problem With the class hidden and when a file is selected from the 2nd instance of the component, the value of this.attachment_filename is updated but in the data of 1st instance of the component!

If I remove the class hidden, it updates the value in the correct instance.

Possible solution use css opacity or width instead of the class hidden.

But is there a reason for this behavior?

Categories: Software

Pages