Vuejs

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

Change CSS class property with Vue.js

Wed, 2017-09-13 13:02

I'm using Vue.js and I want to change a CSS class property. The HTML code which uses the class is the following:

<div class="fillTimerBar"></div>

And the CSS code:

.fillTimerBar { width: 100%; height: 8px; }

From there I want to change the width class property using a computed property from the Vue component.

Which would be correct way if any?

Categories: Software

Vue d3 set attribute callback can't access Vue data property

Wed, 2017-09-13 12:35

I have one component in Vue, and I want to draw two rectangles using d3. I try to set the x and y attribute of the rect element using a callback method defined in the Vue component.

But I can not access the data property set for Vue component inside this callback. Here is my component, I am getting confused further because when I hit the debugger and does console.log(this.svgHeight) in the Chrome DevTools console directly, it does log the svgHeight defined in the data.

<template> <v-container class="travel-pattern"> <v-layout> <v-flex xs12 id='svg-container'> </v-flex> </v-layout> </v-container> </template> <script> /* eslint-disable no-undef */ /* eslint-disable no-unused-vars */ export default { name: 'travel-pattern', data () { return { msg: 'Travel Pattern component', dataset: [{h: 50, w: 100}, {h: 80, w: 200}], svgHeight: 100, svgWidth: 500 } }, methods: { getRectHeight: d => { return d.h }, getRectWidth: d => { return d.w }, getRectX: (d, i) => { return (i * d.w) + 25 }, getRectY: d => { // return 50 debugger let x = this.svgHeight // here x gets undefined. return (x) }, getClickEvent: d => { debugger } }, mounted () { // 1. Draw two rectangles // 2. Each rectangle can be clicked // 3. Once clicked a pop up will appear with a text field // 4. Entering a color in the text field will change the other rectangles color // Create an SVG element var svg = d3.select('#svg-container') .append('svg') .attr('height', this.svgHeight) .attr('width', this.svgWidth) // Create a rectangle for each dataset var rectangles = svg.selectAll('rect') .data(this.dataset) .enter() .append('rect') // Actually draw the rectangles rectangles.attr('x', this.getRectX) .attr('y', this.getRectY) .attr('width', this.getRectWidth) .attr('height', this.getRectHeight) rectangles.on('click', this.getClickEvent) } } </script>
Categories: Software

HTML Tag in Array Value

Wed, 2017-09-13 12:14

The Requirement is to append an HTML element from Array Value to DOM

template: { 0: { h1: '<h1>Hi</h1>' }, 1: { h2: '<h2>Hi</h2>' }, 2: { h3: '<h3>Hi</h3>' } }

I have a VueJS For Loop:

<div v-for="temp in template"> {{ temp.h1}} </div>

DOM :

<h1>hi</h1>
Categories: Software

Ruby on Rails 5.1 & Vue.js 2.4.x – Testing with Karma, Jasmine – How to install?

Wed, 2017-09-13 11:57

I have Rails 5.1.x and Vue.js 2.4.x; I do not mix Rails and Vue.js in the frontend – only Vue.js is used

I added the following packages:

package.json

... "devDependencies": { "jasmine": "^2.8.0", "karma": "^1.7.1", "karma-chrome-launcher": "^2.2.0", "karma-jasmine": "^1.1.0", "webpack-dev-server": "^2.6.1" }, ...

Q1: Where do I do the configuration? In webpack/test.js or some karma.conf.js file

Q2: What is in this conf file?

Q3: Do I need to install karma-webpack?

Categories: Software

Vue2.4+ compile component behavior

Wed, 2017-09-13 11:22

So I've recently started working with Vue js. I'm attempting to dynamically add and remove Vue nodes. It's a bit difficult to describe the issue so I've created a demo to illustrate it.

Vue.component('context', { data() { return { test: '<context></context>', //Dummy recursive data to illustrate issue child: '' } }, methods: { addChild() { this.child = this.test }, removeChild() { this.child = '' } }, computed: { dynamic() { return Vue.compile(this.child) }, style() { return { 'background-color': '#' + randHex(6) } } }, template: ` <div :style="style" @click="addChild" @click.shift="removeChild"> <component :is="dynamic"></component> </div> ` }) new Vue({ el: '#app' }) function randHex(digits) { let hex = Math.floor(Math.random() * Math.pow(16, digits)).toString(16) return '0'.repeat(digits - hex.length) + hex } html, body { height: 100%; overflow: hidden; } div { width: 90%; height: 90%; } <script src="https://unpkg.com/vue@2.4.3/dist/vue.js"></script> <p>Click on the block to add, Shift-Click ro remove. Why does shift clicking always remove all inner blocks and not just the ones as children to the shift clicked block?</p> <div id="app"> <context></context> </div>

Above you will see that Clicking on the colored rectangles adds a inner child as intended. However when you shift click on a rectangle it not only removes its children, but ALL children! (Even ones that are parents to the current node.)

Initially I had thought the click event was "bleeding through" to the lower elements, I did however create a bit more complex test that offset the elements position to not be above one another, this still produced the same strange behavior.

Any help on understanding / resolving this issue would be greatly appreciated.

Categories: Software

How to use .vue files with Rails 5.1

Wed, 2017-09-13 10:42

I currently have one application.js file in which I've put all my Vue.js code, as follows:

import Vue from 'vue/dist/vue.esm'; document.addEventListener('DOMContentLoaded', () => { if(document.getElementById('dashboard-topbar')) { const dashboard = new Vue({ ... do stuff }) } if(document.getElementById('map')) { const map = new Vue({ ... do stuff }) } if(document.getElementById('something-else')) { const something-else = new Vue({ ... do stuff }) } }

but I would like to separate these into their own .vue files. What's the recommended way of doing this?

Thanks!

Categories: Software

Turbolinks causes vue js to load twice on every navigation

Wed, 2017-09-13 10:29

When opening page A - then B and then going back to Page A I will see

You are running Vue in dev mode

beeing logged twice. This also causes my components to flash.

I've added

<meta name="turbolinks-cache-control" content="no-cache">

To all my pages and already use Turbolinks adapter

import TurbolinksAdapter from 'vue-turbolinks' window.Vue.use(TurbolinksAdapter);

Any Ideas on this?

Categories: Software

How to tell when to create a new component?

Wed, 2017-09-13 10:19

I've been looking around behind the logic of when someone shall create a new component in a web application on angularjs / angular but I suppose this is more general and might apply on all component based front end frameworks.

I know that there are some principles like it should be abstract and reusable but is there any solid question which I might ask before creating a new component ?

Categories: Software

Upload file from VueJS app to API in Laravel

Wed, 2017-09-13 10:13

I'm trying to upload a file (Excel sheet) from a front-end app build with VueJS to an API build with Laravel 5.5. I've some form request validation which says to me that The file field is required. So the file doesn't get uploaded to my API at all.

VueJS file upload:

onFileChange(e) { let files = e.target.files || e.dataTransfer.files; if (files.length <= 0) { return; } this.upload(files[0]); }, upload(file) { this.form.file = file; this.form.put('courses/import') .then((response) => { alert('Your upload has been started. This can take some time.'); }) .catch((response) => { alert('Something went wrong with your upload.'); }); }

this.form is a Form class copied from this project but the data() method returns a FormData object instead of a object.

The route:

enter image description here

FormRequest rules:

public function rules() { return [ 'file' => 'required', ]; }

If I look to the Network tab in Chrome DevTools it does seem that the request is send correctly: (image after click).

I've tried a lot of things, like sending the excel as base64 to the api. But then I couldn't decode it correctly. So now I'm trying this, but I can't solve the problem. Any help is much appreciated.

Categories: Software

Unable to display data from Firebase Database using Vue.js

Wed, 2017-09-13 09:52

I have connected my Vue app to my Firebase Database and am able to see the resulting JSON in my Vue Dev Tools when I inspect the page on my localhost, for example:

users:Array[10] 0:Object .key:"99" City:"Richmond" Date of Birth:"9/16" Email:"fakeemail@gmail.com" Gender:"F" Home Phone:"" Ministry:"Campus" Name:"Doe, Jane" State:"VA" 1:Object 2:Object 3:Object etc.

In my App.vue file, I have the following code to output the data:

... <tbody> <tr v-for="user in users"> <td>{{ user.name }}</td> <td>{{ user.city }}</td> <td>{{ user.state }}</td> </tr> </tbody> ...

This outputs a table with the correct number of rows (10), but each table cell is blank. None of the data is printed. I'm guessing my references to the table using user.name, user.city, and user.state are not correct? Can you see if I'm doing something wrong? Thanks!

P.S. I have set the Rules to allow anyone to read/write to this database so I don't think permissions are the issue.

Categories: Software

Vues.js unit test w Karma-Mocha-HeadlessChrome , why message INFO about Vue Devtools?

Wed, 2017-09-13 09:48

running my unit tests, I am always getting this info messsage even if I already added the Devtools extension in my Chrome browser ?

yves$ npm run unit > shopping-list@1.0.0 unit /Users/yves/Developments//shopping-list > cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/ launcher]: Launching browser ChromeHeadless with unlimited concurrency [launcher]: Starting browser ChromeHeadless HeadlessChrome 0.0.0 (Mac OS X 10.12.6)]: Connected on socket s3ED3TVFNjuvVojoAAAA with id 22013100 INFO LOG: 'Download the Vue Devtools extension for a better development experience: https://github.com/vuejs/vue-devtools'

any way to get rid of it ?

Categories: Software

Vue how to ensure async requests from both components have succeeded?

Wed, 2017-09-13 09:36

I have 2 components that each perform an AJAX requests with axios:

axios.get(this.ajaxUrl) .then((response) => {

Both of these components are hooked up to a Vuex store and I need to perform an action that ensure both async requests have succeeded.

To do this I need to have something in place which waits for both successful AJAX requests and only fires at that point.

I is not hard to do this for a single AJAX requests, I could set a property in my store like ajaxSuccess which defaults to false. When that property is being set to true I could simply use a watcher to respond to it and perform my event.

I have used this construct before and it works fine. How would I do this for multiple AJAX requests though?

Categories: Software

How to display space instead undefined and null in vue.js template?

Wed, 2017-09-13 09:32

This is Vue.js template

<strong>{{userdata.phone}}</strong>

When userdata.phone == null or userdata.phone == undefined, I would like to show space. for example

<strong> {{ userdata.phone | !null | !undefined }} </strong>

Is it possible?

Categories: Software

Errors with Vue values containing underscores

Wed, 2017-09-13 09:27

I'm having problems with Vue values that contains underscores, like this:

{{ employee.acf.user_phone }}

I'm getting console errors telling me:

[Vue warn]: Error in render function: "TypeError: Cannot read property 'user_phone' of undefined"

TypeError: Cannot read property 'user_phone' of undefined

However, the data is displayed in the template (it takes a while though), and Vue debugger in Chrome also shows the data correctly. This problem only seems to arise with the values that contains underscores between words. I know I shouldn't start values with underscores, but underscores between words in values should not be problematic right? What could be the problem here?

My data looks like this:

{ "employee":{ "id":1, "name":"name", "url":"", "description":"Lorem ipsum", "link":"http://localhost:8000/employee/john/", "slug":"john", "avatar_urls":{ "24":"http://0.gravatar.com/avatar/7sdb137ab174c6460503dee38a0a86cea?s=24&d=mm&r=g", "48":"http://0.gravatar.com/avatar/7sdb137ab174c6460503dee38a0a86cea?s=48&d=mm&r=g", "96":"http://0.gravatar.com/avatar/7sdb137ab174c6460503dee38a0a86cea?s=96&d=mm&r=g" }, "user_email":"useremail@gmail.com", "acf":{ "user_department":{ "term_id":3, "name":"marketing", "slug":"marketing", "term_group":0, "term_taxonomy_id":3, "taxonomy":"department", "description":"", "parent":0, "count":1, "filter":"raw" }, "user_office":"New York", "user_title":"My fancy title", } } }

Javascript/Vue looks like this:

(function($) { var employeeProfileElement = document.getElementById('vue-employee-profile'); var rest_url = WPsettings.rest_url; var nonce = WPsettings.nonce; if ( employeeProfileElement ) { var EmployeeProfile = new Vue({ el : employeeProfileElement, data() { return { employee: {}, errors: [], loading: true } }, created: function(){ employee = axios.get(rest_url + 'users/' + '1') // add authentication with nonce .then(response => { this.employee = response.data; this.loading = false; }) .catch(e => { this.errors.push(e); console.log(this.errors); }); } }); } })(jQuery);
Categories: Software

V-model multiple field with keys

Wed, 2017-09-13 09:08

Hi I would like to ask if how can I construct my data for multiple field with keys. Currently I'm getting undefined quantity and bidrate.

<td> <div class="field"> <div class="control"> <input v-numeric value="" class="input" type="number" placeholder="0" @keypress="validateQuantity" v-model="selectedContainers[index].quantity" > </div> </div> </td> <td> <div class="field"> <div class="control"> <input v-numeric.decimal class="input" type="number" placeholder="0" @keyup="validateBidRate" v-model="selectedContainers[index].bidrate" > </div> </div> </td>

Here's the screenshot of my UI:

enter image description here

Categories: Software

How to display images that have been fixed orientation image?

Wed, 2017-09-13 07:03

I use collaborate https://github.com/blueimp/JavaScript-Load-Image and https://github.com/blueimp/JavaScript-Canvas-to-Blob to fix orientation

My code in vue component like this :

<template> <div> ... </div> </template> <script> export default { ... data() { return { items: [1,2,3,4,5], clicked: [], selectedImage: null, image: [] } }, methods: { changeImage(item, $event) { const self = this this.selectedImage = $event.target.files[0] loadImage( $event.target.files[0], function (img) { img.toBlob( function (blob) { // create a form const form = new FormData(); form.append('file', blob, $event.target.files[0].name); // define the done handler const onDone = (response) => { if (!$.trim(response)) { alert('No response'); } else { const files = $event.target.files || $event.dataTransfer.files if (!files.length) return; self.createImage(item, response) } } // define th post options const options = { url: window.Laravel.baseUrl+'/product/addImageTemp', type: "POST", data: form, enctype: 'multipart/form-data', processData: false, // tell jQuery not to process the data contentType: false // tell jQuery not to set contentType } // submit the image $.ajax(options).done(onDone); }, $event.target.files[0].type ); }, { maxWidth: 600, canvas: true, pixelRatio: window.devicePixelRatio, downsamplingRatio: 0.5, orientation: true } // Options ); }, createImage(item, response) { const image = new Image() const reader = new FileReader() reader.onload = (e) => { this.image[item] = e.target.result this.$set(this.clicked, item, true) }; reader.readAsDataURL(this.selectedImage) } } } </script>

The code is works

If I upload image, it will fix orientation and save in folder. And also display in browser

My problem is the image displayed in the browser is an image that has not fixed orientation. I want the image shown is a image that had fix orientation image.

Information

I have 5 picture boxes if user uploads the image in box 3, it will show in box 3

Categories: Software

Why fail to call method in vue component if collaborate with a plugin?

Wed, 2017-09-13 05:11

I get reference to fix orientation image from here :

https://github.com/blueimp/JavaScript-Canvas-to-Blob

I try in vue component like this :

<template> <div> ... </div> </template> <script> export default { ... methods: { ... changeImage(item, $event) { ... loadImage( $event.target.files[0], function (img) { img.toBlob( function (blob) { // create a form const form = new FormData(); form.append('file', blob, $event.target.files[0].name); // define the done handler const onDone = (response) => { if (!$.trim(response)) { alert('No response'); } else { const files = $event.target.files || $event.dataTransfer.files if (!files.length) return; this.createImage(item, response) ... } } // define th post options const options = { url: window.Laravel.baseUrl+'/product/addImageTemp', type: "POST", data: form, enctype: 'multipart/form-data', processData: false, // tell jQuery not to process the data contentType: false // tell jQuery not to set contentType } // submit the image $.ajax(options).done(onDone); }, $event.target.files[0].type ); }, { maxWidth: 600, canvas: true, pixelRatio: window.devicePixelRatio, downsamplingRatio: 0.5, orientation: true } // Options ); }, createImage(item, response) { ... } } } </script>

It works. It success upload image in folder. But on the console exist error :

Uncaught TypeError: Cannot read property 'createImage' of undefined

The error here : this.createImage(item, response)

Seems the error because it cannot use this in function (img) {

How can I solve this problem?

I need this plugin to fix orientation image

Categories: Software

Unexpected keyword 'import' in WebPack Django and Vue.js project

Wed, 2017-09-13 01:59

I have a simple project where I am using Django, Webpack and Vue.js. When I build a static bundle upon load it seems like my bundle is not compiled correctly. I get an error in JavaScript console:

[Error] SyntaxError: Unexpected keyword 'import' (anonymous function) (main-dd2bbbf09bf9a252a3c7.js:47)

I tried to keep my webpack.config.js really simple:

var path = require("path"); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { context: __dirname, entry: './frontend/js/main', output: { path: path.resolve('./frontend/bundles/'), filename: "[name]-[hash].js", }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), ], resolve: { extensions: ['', '.js', '.vue', '.json'], }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { } // other vue-loader options go here } }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } } ], }, }

.babelrc looks like this:

{ "presets": [ ["env", { "modules": false }] ] }

main.js (which ultimately blows up) is simple:

import Vue from 'vue' import App from './App.vue' new Vue({ el: '#app', render: h => h(App) })
Categories: Software

Using Framework7+Vue's smart-select with a v-model

Wed, 2017-09-13 01:37

I've tried unsuccessfully to get a v-model to work correctly with the smart-select form, and looking through the component source I can't find where the smart-select value is being saved at all. The framework7-vue docs are frustratingly lacking in terms of showing how to use the framework7 items in an actually useful way.

<f7-list form> <f7-list-item smart-select smart-select-searchbar title="Ladders" smart-select-open-in="popup" v-model="selectedLadders" v-on:change="console.log('onChange')" v-on:input="console.log('onInput')"> <select name="ladders" multiple="multiple" > <option v-for="ladder in LadderConfigs" :key="ladder.key" :value="ladder.key" :input-value="ladder.key">{{ladder.name}}</option> </select> </f7-list-item> </f7-list> ... watch: { selectedLadders(new) { console.log("ladders changed:", new) }, }

Am I missing some hidden field, messed up my implementation, or something else? I already had to find the un-documented input-value prop for the radio select to work, so I wouldn't be surprised if I'm missing something here too.

Thanks!

Categories: Software

How to set Vue.http.post data using Vue to send data to Laravel route?

Wed, 2017-09-13 01:16

I want to send a post request to Laravel backend using Vue.js. I'd like to make it without any extra library. I am making a pure Vue.http.get request and it works like a charm. For testing Laravel route and Controller returned data, I've made a ajax request in my template, which also works fine, returning the correct data. However, when I use Vue, via Vue.http.post('My/Controller/Route',data) it doesn't sends the post data to the Controller.

My Vue.js method:

export default { data() { return { dados: {view: 'dia', pro: [], data: 'Setembro 11, 2017'} } }, method:{ this.dados.pro = this.checkedNames; // returned by another Vue piece of code - console.log() returns the correct data for this var return Vue.http.post('/admin/getAgendamentosPorProfissional', this.dados).then( (response) => { console.log(response.body); }, (response) => { console.log("Error"); console.log(response); console.log(response.body); }); } }

My Laravel Controller function:

public function getAgendamentosPorProfissional(){ // $view = $_POST['view']; // $pro = $_POST['pro']; // $data = $_POST['data']; $post = $_POST; return response()->json(array('post' => $post),200); }

It returns:
{post: Array(0)}

My jQuery AJAX function:

$.ajax({ type:'POST', url:'/admin/getAgendamentosPorProfissional', data: {"data": data, "view": view, "pro": [pro],"_token": "{{ csrf_token() }}"}, success:function(data){ console.log("AJAX - /admin/getAgendamentosPorProfissional"); console.log(data); } });

It returns:

post: data: "Setembro 11, 2017", pro:["75"] view"dia" _token:"6LviacS2KoBqjXxTsFhnTtAQePuEzZ49OMwqBmbM"

It's not a CORS issue, since it returns the correct data from the requested url in laravel. How can I fix this?

Categories: Software

Pages