Software

Is there a way to attach an event handler to a drawer opening and closing?

Vuejs - Sat, 2017-08-12 17:40

I'm working on a game for my son and I would like the game to pause automatically when the drawer is opened. In order to accomplish that, I want to associate a dispatch() call to the drawer opening event.

Categories: Software

Populating table with object containing an array in vuejs?

Vuejs - Sat, 2017-08-12 17:03

I am trying to populate table with an object which contains an array.I am able to successfully do that but i want each task name to have its own row right now they are coming in a single row.

{level_image :"image"level_name:"1"task_name: ["game","taskgame","jenga"]}

<tr v-for="tel in result" :key="tel.level_image" :pey="tel.level_name"> <td>{{tel.level_image}}</td> <td>{{tel.level_name}}</td> <td v-for="task in tel.task_name">{{task}}</td> </tr>
Categories: Software

Download fileResult docx on client side

Vuejs - Sat, 2017-08-12 16:37

I am working on a client-server application, and at the moment i am returning a file result in my web api controller, like this:

FileContentResult result = new FileContentResult(System.IO.File.ReadAllBytes(docDestination), "application/msword") { FileDownloadName = "myFile.docx" }; return result;

on my client side i receive the response like this:

enter image description here

i thaught at begin that the browser detects the file automaticly and fires the download dialog, but no, so i tried to treat the result as a blob like this:

.then(response => { console.log("here lives the response:", response); var headers = response.headers; var blob = new Blob([response.bodyText], { type: headers['application/msword'] }); var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = "Filename"; link.click();

the download fires, but the content is not identified as docx file, and his content is broken.

Any tip on how to do it?

Thanks

Categories: Software

How to filter YouTube URL when entered in a input?

Vuejs - Sat, 2017-08-12 16:22

enter image description here

How do I filter a YouTube URL like above picture? when Copy paste the URL It should automatically detect the YouTube and display like above.

can the process done through Laravel or Vue.js ?

Categories: Software

Why does my vue project show this error?

Vuejs - Sat, 2017-08-12 16:12

Idea show me this :

Starting dev server... ERROR Failed to compile with 1 errors20:37:49

This relative module was not found:

Categories: Software

How to access this.$root from VueJS component when inside a test

Vuejs - Sat, 2017-08-12 15:42

In VueJS 2.4, we can access root data from component thanks to this.$root, like in this JSFiddle:

https://jsfiddle.net/bjg2yL1u/1/

If you click on a button, you can see 'orange' displayed in the console, which is a root data, not owned by the todo-item who triggered it.

Now I am inside a Jasmine test. This test works/run/is green properly.

But the console.log inside todo-item component outputs 'undefined'.

How can I inject data to this.$root instance when inside a test ?

describe("TodoItem", function() { var sut; var message = {text:'word'} beforeEach(function() { var Constructor = Vue.extend(TodoItem); sut = new Constructor({ propsData: { todo: message, } }).$mount(); }); it("Should be able to reverse the given word", function() { // Given expect(sut.todo.text).toEqual('word'); expect($(sut.$el).find('li').text()).toEqual('word'); //When sut.reverseMessage(); // Bang !! problem here. 'undefined' is printed, because there is nothing attached to this.$root when inside a test // Then expect(sut.todo.text).toEqual('drow'); }); });
Categories: Software

Laravel\Vue - Request data empty on a production server

Vuejs - Sat, 2017-08-12 15:16

I have a component where I am uploading a video file, everything works fine on my local machine, and it used to work fine on the production server, until only recently after I have done some work and made changes that I saw that it doesn't work now on the production server:

I am using Vue v. 1.0.28, and this is the upload component:

<template> <div class="card-content col-md-10 col-md-offset-1"> <div v-if="!uploading"> <div class="col-md-12 Image-input__input-wrapper"> Upload video <input type="file" name="video" id="video" @change="fileInputChange" class="Image-input__input" accept="video/*"> </div> </div> <div class="alert alert-danger video-upload-alert" v-if="failed">Something went wrong. Please check the video format and try again. If you need any help please contact our <a>support service.</a></div> <div id="video-form"> <div class="alert alert-info" v-if="uploading && !failed && !uploadingComplete"> Please do not navigate away from this page, until the video has finished uploading. Your video will be available at <a href="{{ $root.url }}/videos/{{ uid }}" target="_blank">{{ $root.url }}/videos/{{ uid }}</a>, once uploaded. </div> <div class="alert alert-success" v-if="uploading && !failed && uploadingComplete"> Upload complete. Video is now processing. <a href="/videos">Go to your videos</a>. </div> <div class="progress" v-if="uploading && !failed && !uploadingComplete"> <div class="progress-bar" v-bind:style="{ width: fileProgress + '%' }"></div> </div> <div class="row"> <div class="col-md-12 form-group"> <label for="title" class="control-label">Title</label> <input type="text" class="form-control" v-model="title"> </div> <!-- <div class="col-md-12 form-group"> <label for="visibility" class="control-label">Visibility</label> <select class="form-control" v-model="visibility"> <option value="private">Private</option> <option value="unlisted">Unlisted</option> <option value="public">Public</option> </select> </div> --> </div> <div class="row"> <div class="col-md-12 form-group"> <label for="description" class="control-label">Description</label> <textarea class="form-control" v-model="description"></textarea> </div> </div> <div class="row"> <div class="col-md-12 form-group"> <button type="submit" class="btn btn-submit" @click.prevent="update">Save</button> </div> </div> <div class="row"> <div class="col-md-12 form-group"> <span class="help-block pull-right">{{ saveStatus }}</span> </div> </div> </div> </template> <script> function initialState (){ return { uid: null, uploading: false, uploadingComplete: false, failed: false, title: null, link: null, description: null, visibility: 'private', saveStatus: null, fileProgress: 0 } } export default { data: function (){ return initialState(); }, methods: { fileInputChange() { this.uploading = true; this.failed = false; this.file = document.getElementById('video').files[0]; var isVideo = this.isVideo(this.file.name.split('.').pop()); if (isVideo) { this.store().then(() => { var form = new FormData(); form.append('video', this.file); form.append('uid', this.uid); this.$http.post('/upload', form, { progress: (e) => { if (e.lengthComputable) { this.updateProgress(e) } } }).then(() => { this.uploadingComplete = true this.uploading = false }, () => { this.failed = true this.uploading = false }); }, () => { this.failed = true this.uploading = false }) } else { this.failed = true this.uploading = false } }, isVideo(extension) { switch (extension.toLowerCase()) { case 'm4v': case 'avi': case 'mpg': case 'mp4': case 'mp3': case 'mov': case 'wmv': case 'flv': return true; } return false; }, store() { return this.$http.post('/videos', { title: this.title, description: this.description, visibility: this.visibility, extension: this.file.name.split('.').pop() }).then((response) => { this.uid = response.json().data.uid; }); }, update() { this.saveStatus = 'Saving changes.'; return this.$http.put('/videos/' + this.uid, { link: this.link, title: this.title, description: this.description, visibility: this.visibility }).then((response) => { this.saveStatus = 'Changes saved.'; setTimeout(() => { this.saveStatus = null }, 3000) }, () => { this.saveStatus = 'Failed to save changes.'; }); }, updateProgress(e) { e.percent = (e.loaded / e.total) * 100; this.fileProgress = e.percent; }, } } </script>

The problem is that on upload in my controller in the store function I am receiving empty request object on the production server, and then it fails to find the video:

class VideoUploadController extends Controller { public function index() { return view('video.upload'); } public function store(Request $request) { $player = $request->user()->player()->first(); $video = $player->videos()->where('uid', $request->uid)->firstOrFail(); $request->file('video')->move(storage_path() . '/uploads', $video->video_filename); $this->dispatch(new UploadVideo( $video->video_filename )); return response()->json(null, 200); } }

I am not sure what is going on, since like I wrote it works fine on the local machine, and there I am sending a request that looks like this:

req: {uid: "1598efd62620bd", video: {}}

What is wrong and how can I fix this?

Categories: Software

Axios interceptor doesn't intercept on page load

Vuejs - Sat, 2017-08-12 11:35

I am implementing JWT into my Vue application for authorization and I refresh my tokens once they are used.

I have used axios interceptors so I can intercept every request to my API backend and this seems to work on login etc... but once I refresh the page the request is made as normal using the last token.

The problem is the axios interceptors don't seem to work at this point, so once the token has been used I can't update it with the new one.

Here's how I'm setting my interceptors:-

window.axios.interceptors.request.use(function (config) { console.log("Sent request!"); return config; }, function (error) { console.log("Failed sending request!"); return Promise.reject(error); }); window.axios.interceptors.response.use(function (response) { console.log("Got headers:", response.headers); if (response.headers.hasOwnProperty('authorization')) { console.log("Got authorization:", response.headers.authorization); Store.auth.setToken(response.headers.authorization); } return response; }, function(err){ console.log("Got error", err); });

I don't get any of the console.log's on page load.

I am setting my interceptors in the root app's beforeMount method. I've tried moving them to beforeCreate and I still get the same issue.

Categories: Software

Resetting Vuex store state, properly

Vuejs - Sat, 2017-08-12 10:26

I have a Nuxt application with the following store / state setting:

const store = () => { return new Vuex.Store({ state: { user: { auth: { isLoggedIn: false }, subscription: { has_a_subscription: false }, current_check_in: {}, current_study_level: {} } }, getters, actions, mutations }) }

I update the state via mutation upon login and also persist the data in localStorage and in a cookie. On Logout I'll clear localStorate and the cookies and also want to reset the state to its initial state:

import { setUser, unsetUser } from '~/utils/auth' var config = require('~/config.js').get(process.env.NODE_ENV) const actions = { nuxtServerInit ({ commit }, { req }) { // TODO }, async login ({ commit }, { payload, $axios }) { try { const { data } = await $axios.post(config.auth.LOGIN, payload) var user = _.pick(data, ['name', // etc]) user.auth.isLoggedIn = true commit('SET_USER', user) // Set the cookie setUser({ key: user.username, payload: user }) } catch (error) { if (error.response && error.response.status === 401) { throw new Error('Bad Credentials') } throw error } }, logout ({ commit }) { unsetUser() commit('CLEAR_STATE') } }

I tried different approaches resetting the state to no avail:

try #1:

CLEAR_STATE: (state) => { console.log('resetting data...') var initialState = { auth: { isLoggedIn: false }, subscription: { has_a_subscription: false }, current_check_in: {}, current_study_level: {} } state.user = Object.assign({}, state.user, initialState) }

try #2: Define functions to return the initial state(s):

CLEAR_STATE: (state) => { console.log('resetting data...') Vue.set(state, 'user', initialStates.user()) }

try #3:

CLEAR_STATE: (state) => { console.log('resetting data...') Vue.set(state.user, 'auth', initialStates.auth()) Vue.set(state.user, 'subscription', initialStates.subscription()) Vue.set(state.user, 'current_check_in', initialStates.current_check_in()) Vue.set(state.user, 'current_study_level', initialStates.current_study_level()) }

The mutation 'CLEAR_STORE' doesn't get recorded in vue dev tools even though the console log 'resetting data' appears. There must be something that I am missing here.

I am using the latest 1.0 release candidate of nuxt:

"@nuxtjs/axios": "^3.1.0", "@nuxtjs/component-cache": "^0.1.3", "@nuxtjs/pwa": "latest", "backpack-core": "^0.4.1", "body-parser": "^1.17.2", "es6-promise": "^4.1.1", "express": "^4.15.3", "firebase": "^4.2.0", "js-cookie": "^2.1.4", "jwt-decode": "^2.2.0", "nuxt": "^1.0.0-rc4", "vuelidate": "^0.5.0", "vuetify": "^0.14.0", "whatwg-fetch": "^2.0.3"
Categories: Software

Bind Styles After Ajax Call

Vuejs - Sat, 2017-08-12 06:57

On mounted(), I make an ajax call which pulls in div-specific data such as position on the screen. The problem is that my custom method to set v-bind:style from the ajax data gets run before ajax is finished, thus no data is there to pull from. What is the best way to set my style after ajax is done?

Ajax call returns something like this: [{name: 'table1', top: 10, left: 25},{name: 'table2', top: 30, left: 100}]

$(function() { var app = new Vue({ el: '#main', data: { tables: [] }, methods: { computeOffsets() { return { top: this.tables.top + 'px', left: this.tables.left+ 'px'} } }, mounted() { $.ajax({ method: 'POST', dataType: 'json', url: base_url + 'tables/getTables/' + event_id }).done(data => { console.log(data); this.tables = data; }); } }); }); .table { position: absolute; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script> <div id="main"> <div class='table' v-for="table in tables" v-bind:style="computeOffsets()"> {{table.name}} </div> </div>

Categories: Software

Getting element that is created with vue2, using jQuery

Vuejs - Sat, 2017-08-12 05:06

I have couple of inputs which I created with v-for and I have structured them like this:

<input class="form-control" type="text" :id="'info[' + client + '][' + index + '][name]'"

So, id of an element is for example info[1][1][name]. I can confirm it in inspector.

Now, I am trying to change it's value. The easiest way seemed jQuery to me, because I need to get field information from another component and write on this input (and I knew the client & index so I could $() easily).

As id of our element is info[1][1][name], I tried using $('#info[1][1][name]) in the console but I couldn't get it. Also tried $('body').find('#info[1][1][name]), but no luck either.

What am I doing wrong?

Categories: Software

How can I use the axios.interceptor in a right way?

Vuejs - Sat, 2017-08-12 03:34

I use vue-cli and this is part of my main.js

import Vue from 'vue' import App from './App' import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, axios) Vue.config.productionTip = false new Vue({ el: '#app', template: '<App/>', components: { App } })

In Vue's single File components' structure, I use axios to replace the ajax.

Vue.use(VueAxios, axios)

It makes axios available in every SFC by referring (this.axios). But when I try to use axios.interceptor, I come across an annoying problem. I want to set axios.interceptor.request and axios.interceptor.reponse for the whole project. however, I can only use this.axios.interceptor.request in a Single File Component and it only work in this file. This is the part code of App.js.

methods: { // interceptor setAxiosInterceptor () { this.axios.interceptors.request.use(config => { this.cover = true return config }, error => Promise.reject(error) ) this.axios.interceptors.response.use(response => { this.cover = false return response }, error => { this.cover = false return Promise.reject(error) }) },

I have to set this.axios.interceptor in every SFC. So how can I set the axios.interceptor for the whole project and make it available in every SFC.

Categories: Software

Component based theming

Vuejs - Sat, 2017-08-12 02:01

I'm a front-end developer. I use my custom made CSS framework with sass. I have some jquery knowledge and a little javascript knowledge. I have heard a lot about angular, react, vue, ember etc. But I don't know how can I use them or how they are useful.

I try to explain my needs with some examples.

1- I use jquery ajax to upload and remove image. For this I need define input file and some javascript codes then style with css. For this I want to use something like below. And all html, css, javascript loads

<imageUpload></imageUpload>

2- I have a nav section in my website. One in the header, one in the footer. They are some except some minor styles. I want to define default nav and have a option to override some values like below.

<myNav></myNav> <myNav place="footer></myNav>

NOTE: All my codes are imaginary. I don't need and backend features. I'm going to use PHP for that. All I need front end things. (html, css, javascript, jquery, interaction, dom manipulation etc)

You don't have to recommend only one framework. I just need which one/ones are suitable for this job

Categories: Software

How to pass global variable from parent to child in Vuejs?

Vuejs - Sat, 2017-08-12 01:52

I have a page called Profile.vue which is structured like this,

<style> </style> <template> <component-1></component-1> <component-2></component-3> <component-3></component-3> </template> <script> import component1 from '...../..' import component2 from '...../..' import component3 from '...../..' export default { name: 'profile', data(){ return{ pagename: 'Profile', mydata: 'This is my data' } } } </script>

How do i make the data available in mydata, to all the components that I am importing,i.e, how can I pass data that would be available to all the components?

Categories: Software

Update value in multidimensional array in Vue

Vuejs - Sat, 2017-08-12 00:50

I understand from the caveats portion of the Vue docs that updating a value in an array in the following manner will not work:

this.arr[idx] = newVal

and that one should use splice(). I am using a 2D array to store grid data, and I am having a difficult time updating the value when a cell in the grid is clicked.

Here is my template:

<tr v-for="(row, rowKey, index) in grid" :key="rowKey"> <th class="row-col-label" >{{rowKey+1}}</th> <td v-for="(col, colKey, index) in row" :key="colKey" @click="selectCell(rowKey, colKey)" :class="{'selected' : cellSelected(rowKey, colKey)}" > {{col}} </td> </tr>

And here is the relevant code for the Vue component:

created () { this.initColHead() this.createSpreadSheet() }, data () { return { selected: '', grid: [], colHead: [' '], isSelected: false } }, methods: { initColHead () { this.colHead.push(...'ABC'.split('')) }, createSpreadSheet () { for (let i = 0; i <= 2; i++) { this.grid[i] = [] for (let j = 0; j <= 2; j++) { this.grid[i][j] = false } } }, selectCell (row, col) { this.isSelected = true console.log(`row ${row} col ${col}`) this.grid[row].splice(col, 1, true) for (let i = 0; i <= 2; i++) { for (let j = 0; j <= 2; j++) { console.log(this.grid[i][j]) } } }, cellSelected (row, col) { return (this.grid[row][col] === true) } }

So I am attempting to add a true value to the cell that is click at the given row col locations provided in the my selectCell method. However, the data in my grid is not updated to reflect the newly added value. How exactly do I update values in a multidimensional array in Vue?

Categories: Software

Adding Mutations to Vuex store as part of Vue Plugin

Vuejs - Fri, 2017-08-11 23:41

I'm creating a small Vue Plugin that allows a user to add a "page notification" from within any component. I've successfully implemented something like:

this.$notifications.add("a message");

And it works! But I've had to register the mutations and actions required for my plugin to work as part of the file that sets up the rest of the store for my app:

export default new Vuex.Store({...})

Is there a way to add actions and mutations to my store from within my plugin? It currently looks like this:

import vuex from './../store'; const MyPlugin = { install(Vue, options) { // 4. add an instance method Vue.prototype.$notifications = { notificationTypes: { 0: "warning", 1: "info" }, add: function (options) { let id = "page-notification-" + (vuex.state.pageNotificationsCreated + 1); let message = options.message || options || "no message"; let notificationType = this.notificationTypes[0]; if(options.notificationType && Number.isInteger(options.notificationType)){ // Map int to string type notificationType = this.notificationTypes[options.notificationType] || notificationType; }else{ // Or use string we were provided ;) notificationType = options.notificationType; } let notification = { id: id, message: message, notificationType: notificationType }; vuex.dispatch('addNotification', notification); } } } }; export default MyPlugin;

Any and all help appreciated!

Categories: Software

Build.js.map not found?

Vuejs - Fri, 2017-08-11 22:20

I have a web app using Webpack and Vue.js. It works perfectly on most of the browsers. However Safari can't find build.js.map, which is not in the directory, and I do not include it anywhere.

Can anyone explain why is it looking for it?

Categories: Software

Watching vuex state change from vuejs component

Vuejs - Fri, 2017-08-11 22:00

I am new to both vue.js and vuex. I have a component that need to dispatch an action when a specific data is available in the state. How can I do this.

Thanks

Categories: Software

Unknown custom element: - did you register the component correctly?

Vuejs - Fri, 2017-08-11 21:34

I'm new to vue.js so I know this is a repeated issue but cannot sort this out.

the project works but I cannot add a new component. Nutrition component works, profile does not

My main.js

import Nutrition from './components/nutrition/Nutrition.vue' import Profile from './components/profile/Profile.vue' var Vue = require('vue'); var NProgress = require('nprogress'); var _ = require('lodash'); // Plugins Vue.use(require('vuedraggable')); // Components Vue.component('nutrition', Nutrition); Vue.component('profile', Profile); // Partials Vue.partial('payment-fields', require('./components/forms/PaymentFields.html')); // Filters Vue.filter('round', function(value, places) { return _.round(value, places); }); Vue.filter('format', require('./filters/format.js')) // Transitions Vue.transition('slide', {enterClass: 'slideInDown', leaveClass: 'slideOutUp', type: 'animation'}) // Send csrf token Vue.http.options.headers['X-CSRF-TOKEN'] = Laravel.csrfToken; // Main Vue instance new Vue({ el: '#app', components: { }, events: { progress(progress) { if (progress === 'start') { NProgress.start(); } else if (progress === 'done') { NProgress.done(); } else { NProgress.set(progress); } }, 'flash.success': function (message) { this.$refs.flash.showMessage(message, 'success'); }, 'flash.error': function (message) { this.$refs.flash.showMessage(message, 'error'); } } });

Profile.vue

<template> <div class="reddit-list"> <h3>Profile </h3> <ul> </ul> </div> </template> <script type="text/babel"> export default { name: 'profile', // this is what the Warning is talking about. components: { }, props: { model: Array, } } </script>

profile.blade.php

@extends('layouts.app') @section('title', 'Profile') @section('body-class', 'profile show') @section('content') <script> window.Laravel.profileData = [] </script> <profile></profile> @endsection

Whenever I try to go to this page I get:

[Vue warn]: Unknown custom element: <profile> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

I tried doing a local component such as

Vue.components('profile', { template: '<div>A custom component!</div>' });

or even I tried adding the profile into the components in vue but still no luck, can anyone point me in the right direction?

Categories: Software

Laravel validation on multiple insert

Vuejs - Fri, 2017-08-11 21:31

I have a db table of sport events. Each event has a year, event name and an event winner.

My admin view for this table allows the events to be grouped by year and inserted in bulk (generally 8 sports events rows at once). I have a table, written in Vue that allows up to 8 sports events rows to be added to the interface, fields populated and submitted. This works well.

The method for this is

public function storeMultiple(Request $request) { $year = $request->year; $newEvents = $request->events; foreach ($newEvents as $key => $value) { DB::table('sport_events')->insert([ 'team_id' => 1, 'sort_order' => $value['sort_order'], 'year' => $year, 'event' => $value['event'], 'winner' => $value['winner'], 'created_at' => Carbon::now(), 'updated_at' => Carbon::now() ]); } }

While I know it's not a great way (the db structure limits me here rather than having year be the key and sport events within) and for such a small and infrequent use case, I'm happy with the performance trade off.

The form is submitted to my route via Axios and everything lands in the database as I'd expect.

Now I'm looking to add validation to the method, ensuring that each event has event name and the winner.

$validator = Validator::make($request->all(), [ 'year' => 'required', 'events.*' => 'required', ]); if ($validator->fails()) { return response()->json([ 'errors' => $validator ]); }

It seems that my submit bypasses the validation checks that I have in place, getting a success status.

My Vue submit method does this

submit () { axios({ method: 'post', url: '/admin/sports', data: { year: this.year, sports: this.sports } }).then((response) => { window.location.href = '/admin/sports' }).catch((error) => { // error }) }

Where am I going wrong in this method?

Categories: Software

Pages