Software
Why fail to call method in vue component if collaborate with a plugin?
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 undefinedThe 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
Unexpected keyword 'import' in WebPack Django and Vue.js project
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) })Using Framework7+Vue's smart-select with a v-model
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!
How to set Vue.http.post data using Vue to send data to Laravel route?
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?
chartjs - multi axis line chart - cannot read property 'min' of undefined
When running the below code without the scales and yAxisID values, it renders a 2 line chart with both lines on the same axis
When adding these elements in order to get a split axis, it returns the js error cannot read property 'min' of undefined and the canvas is blank.
Not sure if his should make a difference, but data is a json object returned through an ajax request by way of a vue.js method.
var ctx = document.getElementById("chart_canvas").getContext('2d') var basic_line = new Chart(ctx, { type: 'line', data: { labels: data.labels, datasets: [{ label: 'Price', yAxisID: 'B', fill: false, borderColor: ["#668cff"], data: data.price }, { label: 'Sales', yAxisID: 'A', fill: false, borderColor: ["grey"], data: data.sales }], options: { scales: { yAxes: [{ id: 'A', position: 'left', }, { id: 'B', position: 'right' }] }, responsive: true, maintainAspectRatio: false } } })Vuejs Slot Parent Child
How do I get these 2 components to work together?
Vue.component('parent', { template: ''+ '<slot name="foo"></slot>'+ '' }); Vue.component('child', { template: ''+ '<div slot="foo">bar</div>'+ '' });I thought I could do something like this but it didn't appear to work
Vue.component('parent', { components: [ 'child' ], template: ''+ '<slot name="foo"></slot>'+ '' });Here is a JS Fiddle https://jsfiddle.net/3fjmLL52/
Vuejs router beforeEach : if state is true, run code, else load async data into state, then run same code
I'm using VueJS, VueRouter and VueX in my SPA.
I want my app to load some data at start up, required under multiple routes. This data is stored in the VueX's state.
Here's what I've done with my router, with explanations in the comments, hoping it's clear enough :
and here is what I put in the created method of the main Vue instance :
created() { if (!store.state.startUp) { Promise.all([ store.dispatch('getSomeData1'), store.dispatch('getSomeData2'), ]) .then(() => { store.commit('setStartUp'); // set the state flag property to true }); } }thanks !
Mock backend in nightwatch.js tests
In my Vue.js app I'm using nightwatch to test my app. I have the following spec:
module.exports = { 'wrong email or password': function (browser) { const devServer = browser.globals.devServerURL var nock = require('nock'); var couchdb = nock('http://localhost:3000/') .get('api/v1/login') .reply(401, { error: 'dupa' }); browser .url(devServer + '/login') .setValue('input[type=email]', 'email@example.com') .setValue('input[type=password]', 'password') .click('.login') .assert.containsText('#app', 'Niepoprawny email lub hasło.') .end() } }In my test I'm trying to use https://github.com/node-nock/nock. But unfortunately this not mocks any requests. What I'm doing wrong?
Vue.js filter a list
I am new to Vue.js. I'm trying to display a filtered list based on the value of another object. The select sets the value of the object called activeSet. That value is the key in the sets object. If that keys value is greater than 0 I want to display it in the list and sort by it. Here is my code:
JS
var vm = new Vue({ el: '#app', data: { activeSet: 'all', computed: { activeContents: songs.filter(function(song) { return (song[activeSet] > 0); }) }, songs: { a: { title: 'Hound Dog', all: 0, set1: 2 }, b: { title: 'Long Gone', all: 1, set1: 0 }, b: { title: 'Novermber Rain', all: 2, set1: 3 } }, sets: { all: { name: 'All Songs' }, set1: { name: 'Acoustic' } } } })HTML
<div id="app"> <select v-model="activeSet"> <option v-for="(set,key) in sets" :value="key">{{set.name}}</option> </select> <ul id="menu"> <li v-for="(song,key) in activeContents" :id="key" :is-active="song.show" :key="key" @click="activeSong=key">{{ song.title }}</li> </ul> </div>Fiddle Here is the fiddle
Sidenote: If the value is above 0 it needs to be included and then sorted by that value. I haven't even dived into sorting yet so bonus points if you can sort by the value of those that are greater than 0.
Unable to load module with inject-loader
In my vue.js project I have the following file at src/api/user.js
import { HTTP } from '@/services/http' export const user = { login (email, password) { return HTTP.post('v1/login', { email: email, password: password }) } }I'm trying to load this file using inject-loader inside my specs:
const actionsInjector = require('inject-loader!../../../../src/api/user')it returns me following error:
Module not found: Error: Can't resolve '../../../../src/api/user' in '/home/mateusz/projects/e_lessons_frontend/test/unit/specs/store/user'How can I fix that?
UPDATE:
After adding one extra ../ I have new error:
Error: Some of the injections you passed in are invalid. Valid injection targets for this module are: - @/services/http The following injections were passed in: - @/api/user The following injections are invalid: - @/api/userThis caused by this line of code in my tests:
// create the module with our mocks const actions = actionsInjector({ '@/api/user': { login (email, password) { return { token: 'dupa' } } } })Any ideas?
How to retrieve User name in Vue component with Laravel
I have a vue component that will send a message and I want to send the logged in user name. I'm using laravel 5.5
methods:{ sendMessage(){ this.$emit('messagesent', { message:this.messageText, user: { name : {{Auth()::user()->name}} //Here is where it should be } }); this.messageText = ''; } }I already tried using
{{Auth()::user()->name}} Auth()::user()->nameBoth give errors. How can I retrieve the name?
VueJS (another) virtual scroll implementation
I'm trying to implement virtual scroll for items with variable heights. Every other implementation I've seen so far requires you to specify the height when declaring the module.
I have the list implemented as follows:
<div class="main" ref="main" @scroll="handleScroll" > <div :style="{ 'margin-top':padTop+'px', 'margin-bottom':padBottom()+'px' }"> <div v-for="i in maxDisplayed"> <slot :name="'s-' + (i + startIndex - 1)">{{i + startIndex - 1}}</slot> </div> </div> </div>The handleScroll function (the one failing) is this:
handleScroll (e) { if (!this.$refs.main || this.$refs.main.scrollTop == undefined) return; //can't calculate if there's nothing displayed // top of the items list container relative to the page top let mainTop = this.$refs.main.getBoundingClientRect().top; // bottom position of the first "displayed" item let itemTop = this.$refs.main.children[0].children[0].children[0].getBoundingClientRect().top; let itemBottom = this.$refs.main.children[0].children[0].children[0].getBoundingClientRect().bottom; if (itemBottom < mainTop && (Object.keys(this.$slots).length > (this.startIndex + this.maxDisplayed))) { this.startIndex ++; this.heights.push(this.$refs.main.children[0].children[0].children[0].clientHeight); } else if (itemTop > mainTop && (this.startIndex > 0)) { this.heights.pop(); this.startIndex = Math.max(this.startIndex - 1, 0); } },So far I have the code working perfectly when user is scrolling relatively slowly. But it fails when you scroll fast through the list. I suspect it has something to do with it not being able to catch all the children flying past the scroll window. Any help would be appreciated.
v-if not working on template tag
According to the Vue documentation I should be able to add the v-if condition to the <template> tag:
<template v-if="false"> <div>Invisible text</div> </template>But this will not hide the element, but it does work when added to the child element:
<template> <div v-if="false">Invisible text</div> </template>Any suggestions?
I'm including the template in another .vue file:
<template> <div id="app"> <H1 class= "main-title">Title</H1> <span class="components"> <testtemplate></testtemplate> </span> </div> </template>Content Security Polisy (CSP) - why I need 'unsafe-eval' rule?
I am trying to set CSP headers in my Vue 2.0 app and I have a problem with 'eval' policy.
When I use 'unsafe-eval' - it's all working fine. But when I get rid of it (I know I should) my scripts stop working. There is no error in console. But if I put eval() somewhere in my code intentionally - I get error in console.
I searched whole project (including libs) for "eval" and "new Function" but I can't find any usage of them.
So maybe there are some other functions which meet 'eval' rules? I am using Vue, but my code is built with Browserify + vueify.
vuejs form computed property
I have a simple form in VueJS that I would like to have a computed property for one of the form fields. I would like the computed property to be calculated as the user inputs data and then saved as a data property before submitting the form to the server.
<form> <div> <h3>Revenue</h3> <input type="text" v-model="formData.revenue"> </div> <div> <h3>Expenses</h3> <input type="text" v-model="formData.expenses"> </div> <div> <h3>Operating Income</h3> <input type="text" v-model="formData.operatingIncome"> </div> </form>JS
new Vue({ el: '#app', data: { formData: {} }, computed: { operatingIncome() { return this.formData.revenue - this.formData.expenses; } } });The computed property for operatingIncome does not calculate unless I explicitly create properties for revenue and expenses within formData data object and change the to a string interpolation. Any suggestions on how to make this work?
Show user-friendly error messages in Vue application
As with any application a number of things can go wrong sooner or later. I have a large Vue application that sometimes throws some errors (I know, it shouldn't, but sometimes it does anyway) and I'd like to show a friendly message to the user so they won't be stuck waiting. Like a "generic error handler" of some kind on the window object.
I tried this: javascript: how to display script errors in a popup alert? but it does not fire.
Any other suggestions?
Vue values not recognized in template
Trying out Vue for the first time and having some problem with some values not beeing recognized in the template even though they are set when checking with the Chrome Vue debug tool.
I'm doing this in a Wordpress context if that matters, with an inline template. I stripped down a lot of non-important code in my example below to just focus on the loader. I'm setting the loading value to true and here I'm not changing it anywhere. When loading the page I can see the spinner briefly then it disappears. However the value of loading is true when I check with debug tool. What am I doing wrong?
Javascript:
(function($) { var employeesListingElement = document.getElementById('vue-employees-listing'); if ( employeesListingElement ) { var EmployeesListing = new Vue({ el : employeesListingElement, data() { return { employees: [], filter: '', errors: [], loading: true } } }); } })(jQuery);PHP
<div id="vue-employees-listing"> <div v-if="employees.loading" class="ajax-loader"> <img src="<?php echo get_theme_file_uri('/spinner.svg'); ?>"> </div> </div>Update one of the multiple component's props in Vue.js from outside
Can't find a way to update a specific component's prop from outside of the component.
I have an App.js which loads all components in .vue format. What a basically do is I import a counter.vue inside the App.js, and want to modify one of the specific component's data.
Main file App.js:
Vue.component('counter', require('./components/Counter.vue')); export const App = window.App = new Vue({ el: '#app', methods: { } });Here is a Counter.vue file:
<template> <span class="counter">{{ number }}</span> </template> <script> export default { props: ['name', 'number'], }; </script>In my HTML I have multiple counter instances:
<counter name="cnameA" number="10"></counter> <counter name="cnameB" number="20"></counter> <counter name="cnameC" number="30"></counter>How to I increment a counter with name cnameB by 1 ?
I tried to use a #watch approach, but it's not exactly what I need.
Vue.js datepicker with vertically scrolling month/day/year
I saw an example datepicker for use with vue.js 2 a few days ago. The thing that was different about it was that when you click on the input box, instead of opening a calendar-type user interface, each part of the date (month, day, year) scrolled vertically. I think there was some animation, too. It looked really polished.
Spent all morning looking for it again, but I can't find it. Can someone please help me locate this component?
How to fetch local html file with vue.js?
I am following this example
I am trying to load a html file with vue.js and add into my template.
my attempt:
HTTML:
<html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="/Static/content/css/foundation.css"> <link rel="stylesheet" type="text/css" href="/Static/content/css/spaceGame.css"> </head> <body> <div id="app"> <div class="grid-container"> <div class="grid-x grid-padding-x"> <div class="large-12 cell"> <h1>Welcome to Foundation</h1> </div> </div> </div> <div class="grid-x grid-padding-x"> <div class="large-4 columns"></div> <div class="large-8 columns"> <component :is="currentView"></component> </div> </div> </div> <!-- Footer --> <script src="https://unpkg.com/vue"></script> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="/Static/scripts/foundation.js"></script> <script type="text/javascript" src="/Static/scripts/what-input.js"></script> <script type="text/javascript" src="/Static/scripts/space.js"></script> </body> </html>script:
$(function() { $(document).foundation() var myData = '../../Views/login.html'; Vue.component('manage-posts', { template: myData, }) Vue.component('create-post', { template: '#create-template' }) new Vue({ el: '#app', data: { currentView: 'manage-posts' } }) });Errors:
above I get the following:
- Component template requires a root element, rather than just text.
changing var myData = '../../Views/login.html';
to
var myData = '<div>../../Views/login.html</div>';gets rid of that error but...how do I load the actual html file?
I am new to single page applications and to vue.js, been at this for some time now and can't figure it out.