Software
Minimal examples with external .vue component files not working
I am starting with the snippets in this question How to use multiple vue components on single page? The following example works with vue build app.vue, but it does not work if I set up a simplest server and visit index.html.
index.html:
<!DOCTYPE html> <html> <head> <title>Test</title> <meta charset="utf-8"> <script type="text/javascript" src="jspm_packages/system.js"></script> <script type="text/javascript" src="config.js"></script> </head> <body> <div id="app"></div> <script type="text/javascript"> System.import('app.js'); </script> </body> </html>app.js:
import Vue from 'vue/dist/vue.js' window.onload = function() { new Vue({ el: '#app', render: h => h(app) }) }app.vue:
<template> <qwop></qwop> </template> <script> import qwop from 'qwop.vue' export default { components: { 'qwop': qwop } } </script>qwop.vue:
<template> <div>Hello</div> </template>Through running vue build app.vue, a web server is launched and I can see "Hello" in the web page. But nothing shows if I create a web server by for example python -m http.server and visit index.html. Anything wrong with my index.html and app.js?
How to get id from a loop's item in vue.js?
I have a loop like this:
<div class="jokes" v-for="joke in jokes"> <strong>{{joke.body}}</strong> <small>{{joke.upvotes}}</small> <button v-on:click="upvote"><i class="fa fa-arrow-down"></i></button> <div>I need to get joke.id so that I can post it to backend and increment the votes.
The method should be something like this:
methods: { upvote: function(e) { axios.post( this.BASE_URL + "/api/joke/" + this.joke.id + "/upvote", { token: 'secret', }).then(function(data){ console.log(data); }); } },How can I achieve this?
VueJS + Firebase saving an Array with Keys
Some Context... I have a list of players in a hockey league. For each game played I want to save a gamesheet with the players of the home team and visiting team that would include their game stats. I want the player .key from the full list of players to match the player .key of the stored gamesheet.
The issue I'm having is storing the array of the home/visitor teams to Firebase.
The array for 'homeTeam' is the following:
[ { "name": "Steve", "number": "10", "position": "F", ".key": "-KrbKovnJe2uxU2h1Aec" }, { "name": "Carl", "number": "32", "position": "F", ".key": "-KrbKovnJe2uxU2h1Aec" } ]
I can save individual records with the following:
gamesheetRef.child(gameinfo['.key']).child('home').child(this.homeTeam[0]['.key']).set({name: this.homeTeam[0].name})
This saves as the correct structure in Firebase:
- gamesheet
- -KonukQ9Pf7ksy9jvgo3
- home
- -KrbKovnJe2uxU2h1Aec
- name: "Steve"
How can I save the entire array like this, using the .key(s) from the array?
Loading in local fonts with webpack 2 and the vue-cli
I'm using the vue-cli webpack template and I'm trying to load in local fonts in my project. I'm having trouble getting the path to my fonts correct. How should my path look like?
I found some information about what I might be doing wrong but I couldn't figure it out: https://github.com/webpack-contrib/sass-loader#problems-with-url
File structure:
In my _fonts.scss:
// Webfont: LatoLatin-Regular @font-face { font-family: 'LatoLatinWeb'; src: url('../assets/fonts/LatoLatin-Regular.eot'); /* IE9 Compat Modes */ src: url('../assets/fonts/LatoLatin-Regular.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('../assets/fonts/LatoLatin-Regular.woff2') format('woff2'), /* Modern Browsers */ url('../assets/fonts/LatoLatin-Regular.woff') format('woff'), /* Modern Browsers */ url('../assets/fonts/LatoLatin-Regular.ttf') format('truetype'); font-style: normal; font-weight: normal; text-rendering: optimizeLegibility; }Webpack.base.config.sj:
{ test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('fonts/[name].[hash:7].[ext]') } }Utils.js:
return { css: generateLoaders(), postcss: generateLoaders(), less: generateLoaders('less'), sass: generateLoaders('sass', { indentedSyntax: true }), scss: generateLoaders('sass').concat( { loader: 'sass-resources-loader', options: { resources: path.resolve(__dirname, '../src/styles/_variables.scss') } } ).concat( { loader: 'sass-resources-loader', options: { resources: path.resolve(__dirname, '../src/styles/mixins/_mixins.scss') } } ).concat( { loader: 'sass-resources-loader', options: { resources: path.resolve(__dirname, '../src/styles/_fonts.scss') } } ), stylus: generateLoaders('stylus'), styl: generateLoaders('stylus') }How do I load my local fonts in with vue-cli webpack template?
Vue JS prop in component always undefined
I have a component. Once I select a category I need to get the ID and also a boolean which checks if the category has a subcategory, if it does I do a API call to fetch the subcategories.
Html:
<material-selectcat v-model="catId" name="category" id="selcat"> <option v-for="cat in cats" :value="cat.cat_id" :subcat="cat.has_subCat" v-text="cat.category_name"></option> </material-selectcat>Component:
<template> <select><slot></slot></select> </template> <script> export default { props: ['value', 'subcat'], watch: { watcher: function() {} }, computed: { watcher: function() { this.relaod(this.value); this.fetchSubCategories(this.value, this.subcat); } }, methods: { relaod: function(value) { var select = $(this.$el); select.val(value || this.value); select.material_select('destroy'); select.material_select(); }, fetchSubCategories: function(val, sub) { var mdl = this; var catID = val || this.value; console.log("sub: " + sub); mdl.$emit("reset-subcats"); if (catID) { if (sub == 1) { if ($('.subdropdown').is(":visible") == true) { $('.subdropdown').fadeOut(); } } else { axios.get(URL.API + '/subcategories/' + catID) .then(function(response) { response = response.data.subcatData; response.unshift({ subcat_id: '0', subcategory_name: 'All Subcategories' }); mdl.$emit("update-subcats", response); $('.subdropdown').fadeIn(); }) .catch(function(error) { if (error.response.data) { swal({ title: "Something went wrong", text: "Please try again", type: "error", html: false }); } }); } } else { if ($('.subdropdown').is(":visible") == true) { $('.subdropdown').fadeOut(); } } } }, mounted: function() { var vm = this; var select = $(this.$el); select .val(this.value) .on('change', function() { vm.$emit('input', this.value); }); select.material_select(); }, updated: function() { this.relaod(); }, destroyed: function() { $(this.$el).material_select('destroy'); } } </script>But inside the fetchSubCategories() function this line always returns undefined console.log("sub: " + sub);
If I check the Vue tab in my chrome inspector I can see that all data exist:
cat_id:0 category_name:"All Subcategories" has_subCat:0But why doesnt has_subCat get passed as a prop?
vue 2 props undefined
Please help! I have 'undefined' props in child template.
Main js:
// some code before window.Vue = require('vue'); import EventBus from '../components/event-bus'; // some code after Vue.component('calendar-select', require('../components/admin/calendar_select.vue')); const app = new Vue({ el: '#app', data: function() { return { isActiveCalendar: true } }, methods: { toggleCalendar() { this.isActiveCalendar = !this.isActiveCalendar; } }, mounted() { EventBus.$on('toggleCalendar', this.toggleCalendar); } });After i create template like this:
<template> <div class="custom-select" v-bind:class="{ active: isActiveCalendar}" > <div class="box flex" v-on:click="toggleCalendar" > <span>Calendar</span> <img src="/assets/img/admin/arrow-down.png" alt="#"> </div> </div> </div> </template> <script> import EventBus from '../event-bus'; export default { // ------- start props: ['isActiveCalendar'], data: function() { return { } }, methods: { toggleCalendar: function(event) { console.log(this.isActiveCalendar) EventBus.$emit('toggleCalendar'); } } // ------- end } </script>When i do console.log on this.isActiveCalendar, the variable is undefined. And in Vue plugin for Chrome is same thing.
Please, tell me, what i do wrong!
Thanks!
vuejs 2 observation doesn't work
I can't figure out why vuejs observation don't work on a very simple scenario. When the model "asker" is updated, computed props should automagically update value to 3. Why is this not working ? Fiddle is here https://jsfiddle.net/w1zz9cjs/3/
<div id="simulator"> <c-simulator-form v-bind:subject="asker"></c-simulator-form> </div> Vue.component('c-simulator-form', { props: ['subject'], template: '<div class="c-simulator-form">{{thesize}}</div>', computed: { thesize: function() { return _.size(this.subject); } } }); var vm = new Vue({ el: '#simulator', data: { asker: { a: 1, b: 2 } } }); vm.asker['c'] = 3;user php captcha in vuejs component
in laravel 5.4.20 and vuejs2. i want to use a simple code captcha in my vue modal component (i dont want to use recaptcha). how can i do it??
im using mewebstudio captcha like this :
Route::any('captcha-test', function() { if (Request::getMethod() == 'POST') { $rules = ['captcha' => 'required|captcha']; $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { echo '<p style="color: #ff0000;">Incorrect!</p>'; } else { echo '<p style="color: #00ff30;">Matched :)</p>'; } } $form = '<form method="post" action="captcha-test">'; $form .= '<input type="hidden" name="_token" value="' . csrf_token() . '">'; $form .= '<p>' . captcha_img() . '</p>'; $form .= '<p><input type="text" name="captcha"></p>'; $form .= '<p><button type="submit" name="check">Check</button></p>'; $form .= '</form>'; return $form; });but it just work in php documents (i need in vue component)
Vue watch multiple props in component
I have a <select> component that looks like this:
<script> export default { props: ['value'], watch: { value: function(value) { this.relaod(value); this.fetchSubCategories(value); } }, methods: { relaod: function(value) { var select = $(this.$el); select.val(value || this.value); select.material_select('destroy'); select.material_select(); }, fetchSubCategories: function(value) { var mdl = this; var catID = value || this.value; mdl.$emit("reset-subcats"); if (catID) { axios.get(API.URL + '/subcategories/' + catID) .then(function(response) { response = response.data.subcatData; response.unshift({ subcat_id: '0', subcategory_name: 'All Subcategories' }); mdl.$emit("update-subcats", response); $('.subdropdown').fadeIn(); }) .catch(function(error) { if (error.response.data) { swal({ title: "Something went wrong", text: "Please try again", type: "error", html: false }); } }); } } else { if ($('.subdropdown').is(":visible") == true) { $('.subdropdown').fadeOut(); } } } }, mounted: function() { var vm = this; var select = $(this.$el); select .val(this.value) .on('change', function() { vm.$emit('input', this.value); }); select.material_select(); }, updated: function() { this.relaod(); }, destroyed: function() { $(this.$el).material_select('destroy'); } } </script>
But now the API has added one more value which says if the current category has a subcategory, if it does then I must call the API for that subcategory once a selection has been made.
So I have added the value to my props like this: props: ['value', 'hasSubCat'],
What I was thinking now is that I only will run the function fetchSubCategories(value) if the prop hasSubCat of the selected item is = 1.
But how can I watch multiple props? Right now my code only watch the prop value and calls the API once a item in the <select> has been selected if I try to use this.hasSubCat inside my fetchSubCategories() function it will only return undefined. So how can I keep track of what value the hasSubCat prop has?
How to add current year for copyright in vie.js?
I want to display ©year in my webpage.
How do I do the following in vue.js
document.write( new Date ().get
.Net web api creates new session for each request
We're developing a web api, which is connected by a vue js app, for the client side, we are using vue-resource to post a request to api. We have to keep some data on session, but for each request, web api creates new session. We tried all the topics at stackoverflow that are related with the problem, but any of them couldn't solve the problem.
Global.asax
protected void Application_PostAuthorizeRequest() { if (IsWebApiRequest()) HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required); } private bool IsWebApiRequest() { var apiPrefix = "~/api"; return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(apiPrefix, StringComparison.CurrentCultureIgnoreCase); } protected void Session_Start(object sender, EventArgs e) { } protected void Session_End(object sender, EventArgs e) { }Vuejs send array json
There is a database. Containing two tables - a recipe and a flavor , between which one-to-many relationship. One recipe - a lot of flavor. I send data from the vue. How do I prepare the data for transmission?
var vm = new Vue({ el: '#my_view', data: { recipeslist: [], recipe: [], newrecipe: {} }Build QR code scanner using Vue.js
I wanted to build a QR code SCANNER using Vue.js but I am not able to find any resources.Can someone please help me to get some resources.I am new to Vue.js so I am not able to find any resources/packages to build the QR code scanner
Laravel - Inserting users to database through vue.js component
I am creating small project in Laravel. I made a small CMS based on vue.js (it is component based SPA application) and now I (as Admin) want to insert manually users to database (username, email, password, and boolean isAdmin) from vue's component.
And questions is how can I do that in secure way?
How to pass props to all routes in vue.js?
I want to pass BASE_URL to all components. My App.js is like:
<template> <router-view></router-view> </template> <script> import addJoke from './components/addJoke.vue' import showJokesAll from './components/showJokesAll.vue' export default { components: { 'add-joke': addJoke, 'show-jokes-all': showJokesAll }, data () { return { BASE_URL : 'http://127.0.0.1:8090' } } } </script> <style> </style>And the routes.js:
import showJokesAll from './components/showJokesAll.vue'; import addJoke from './components/addJoke.vue'; export default [ {path:'/', component: showJokesAll, props: {BASE_URL: 'http://127.0.0.1:8090'} }, {path:'/add', component: addJoke, props: {BASE_URL: 'http://127.0.0.1:8090'} } ]and in showJokesAll component I have:
<script> import axios from 'axios'; export default { name: 'showJokesAll', props: ['BASE_URL'], data () { return { jokes:[] } }, methods: { }, created() { axios.get( BASE_URL + '/api/jokes').then( response => this.jokes = response.data); } } </script>But the components is not received BASE_URL.
[Vue warn]: Error in created hook: "ReferenceError: BASE_URL is not defined"
How can I fix this?
Uncaught (in promise) 500 (Internal Server Error) BadMethodCallException
I use vue 2.0 and Laravel 5.4
I trying to build a matching system
that has a dynamic vue component in it (i.e when someone likes another person it immediately tells you that you have liked that person and/or when accepting it immediately tells you that you're a match)
but the component keeps loading, and in my dev-tools it tells me it has an internal server error(500) (+ Uncaught (in promise))
and in my network it shows a BadMethodCallException--> Call to undefined method Illuminate\Database\Query\Builder::matches_with()
i'v included the component in my app.js file (resources)-->> Vue.component('match', require('./components/Match.vue'));
my Vue file
<template> <div> <p class="text-center" v-if="loading"> Loading... </p> <p class="text-center" v-if="!loading"> <a v-if="status == 0" @click="like_user"> <span title="I like you" class="send-heart"></span> </a> <a href=""><span title="I like you to" class="pending" v-if="status == 'pending'" @click="mutual_like">accept</span></a> <a href=""> <span title="You like this person" class="pending" v- if="status == 'waiting'"></span> </a> <span v-if="status == 'match'" title="Chat" class="chat"></span> </a> </p> </div> </template> <script> export default { mounted() { this.$http.get('/check_match_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: { like_user() { this.loading = true this.$http.get('/like_user/' + this.profile_user_id) .then((r) => { if (r.body == 1) this.status = 'waiting' this.loading = false }) }, mutual_like() { this.loading = true this.$http.get('/mutual_like/' + this.profile_user_id) .then((r) => { if (r.body == 1) this.status = 'match' this.loading = false }) } } } </script>my Controller
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use App\Profile; use Illuminate\Support\Facades\Event; use App\User; use App\Matches; use App\Traits\Matchable; use DB; class MatchesController extends Controller { use Matchable; public function check($id){ if (Auth::user()->matches_with($id) === 1) { return [ "status" => "match" ]; } if(Auth::user()->has_pending_like_request_from($id)) { return [ "status" => "pending" ]; } if(Auth::user()->has_pending_like_request_sent_to($id)) { return [ "status" => "waiting" ]; } return [ "status" => 0 ]; } public function like_user($id) { //notify users return Auth::user()->like_user($id); } public function mutual_like($id) { //sending nots return Auth::user()->mutual_like($id); } public function matches() { $uid = Auth::user()->id; $match1 = DB::table('matches') ->leftJoin('users', 'users.id', 'matches.recipient_id') // who is not loggedin but send request to ->where('status', 1) ->where('sender_id', $uid) // who is loggedin ->get(); //dd($friends1); $match2 = DB::table('matches') ->leftJoin('users', 'users.id', 'matches.sender_id') ->where('status', 1) ->where('recipient_id', $uid) ->get(); $matches = array_merge($match1->toArray(), $match2->toArray()); return view('matches', compact('matches')); } }my Trait use App\Matches; trait Matchable { public function like_user($recipient_id) { if($this->id === $recipient_id) { return 0; } if($this->matches_with($recipient_id) === 1) { return "You are already a match!"; } if($this->has_pending_like_request_sent_to($recipient_id) === 1) { return "You already liked this person."; } if($this->has_pending_like_request_from($recipient_id) === 1) { return $this->like_user($recipient_id); } $match = Matches::create([ 'sender_id' => $this->id, 'recipient_id' => $recipient_id ]); if($match) { return 1; } return 0; } public function mutual_like($sender_id) { if($this->has_pending_like_request_from($sender_id) === 0) { return 0; } $match = Matches::where('sender_id', $sender_id) ->where('recipient_id', $this->id) ->first(); if($match) { $match->update([ 'status' => 1 ]); return 1; } return 0; } public function matches() { $matches = array(); $m1 = Matches::where('status', 1) ->where('sender_id', $this->id) ->get(); foreach($f1 as $match): array_push($matches, \App\User::find($match->recipient_id)); endforeach; $matches2 = array(); $m2 = Matches::where('status', 1) ->where('recipient_id', $this->id) ->get(); foreach($m2 as $match): array_push($match2, \App\User::find($match->sender_id)); endforeach; return array_merge($matches, $match2); } public function pending_like_requests() { $users = array(); $matches = Matches::where('status', 0) ->where('recipient_id', $this->id) ->get(); foreach($matches as $match): array_push($users, \App\User::find($match->sender_id)); endforeach; return $users; } public function matches_ids() { return collect($this->matches())->pluck('id')->toArray(); } public function matches_with($user_id) { if(in_array($user_id, $this->matches_ids())) { return 1; } else { return 0; } } public function pending_like_requests_ids() { return collect($this->pending_like_requests())->pluck('id')->toArray(); } public function pending_like_requests_sent() { $users = array(); $matches = Matches::where('status', 0) ->where('sender_id', $this->id) ->get(); foreach($matches as $match): array_push($users, \App\User::find($match->recipient_id)); endforeach; return $users; } public function pending_like_requests_sent_ids() { return collect($this->pending_like_requests_sent())->pluck('id')- >toArray(); } public function has_pending_like_request_from($user_id) { if(in_array($user_id, $this->pending_like_requests_ids())) { return 1; } else { return 0; } } public function has_pending_like_request_sent_to($user_id) { if(in_array($user_id, $this->pending_like_requests_sent_ids())) { return 1; } else { return 0; } } }
my Model
namespace App; use Illuminate\Database\Eloquent\Model; class Matches extends Model { protected $fillable = ['sender_id', 'recipient_id', 'status',]; }
VueJs draggable sortable cancel adding element without cancel the drag preview
I am working with draggable and sortable with vueJS, and i am trying to accomplish a thing, basicly i have 2 lists, the first one is a list with some sections like (table, paragraph ...) the second one are building blocks with this sections, but basicly the flow i need is, drag a element from list1 to list2, but don't add the element this is important because i need to open a modal first to set the properties of the element that will be added, and then add it to the futureIndex.
At the moment i have a solution where i can do almost what i need, i just need to understand how to cancel the addition of the element without struggling with the preview of the dragging, with preview i mean this:
i wanna see the adition of the elment at the middle.
So my first list i have done this:
<draggable v-model="sectionList" class="dragArea" @end="changeView()" :move="moveItem" :options="{group:{ name:'sections',pull:'clone',put:false }}"> <div v-for="(section, index) in sectionList" class="card card-color list-complete-item"> <div class="card-block"> <h4 class="card-title text-center">{{section.text}}</h4> </div> </div> </draggable> methods: { addParagraph() { this.$set(this.paragraph, 'key', this.key); this.$set(this.paragraph, 'text', this.text); this.$set(this.paragraph, 'fontSize', this.fontSize); this.$store.commit("appendToDocument", this.paragraph) }, changeView: function () { this.$store.commit("changeCurrentView", this.sectionList[this.dragedIndex].component); this.show(); }, show() { this.$modal.show('modalSection'); }, hide() { this.$modal.hide('modalSection'); }, currentIndex(evt) { console.log(evt.draggedContext.index); }, moveItem(evt) { // future index of the modal that will be draged console.log(evt.draggedContext.futureIndex); this.dragedIndex = evt.draggedContext.index; } },the second list is not that important, as long as i can understand with this post, how to move the item without adding it and see the preview. i had added the return false at the end but with that i can't see the preview and i can't drag elements between the same list.
Any help with this?
Saving state on back button press in vue-electron
I want to make a desktop app in vue-electron. I am new to both vue.js and electron. I am having some problems while managing state.
When I click on login button https://cloudup.com/cFl9MTY6cnn I send data i.e sessionId and username to next screen https://cloudup.com/c76fmL8OGbF and on this screen I display these props https://cloudup.com/csahnc6Z04J using this code https://cloudup.com/cdR0F6Qyt-3 but as I go to the third screen https://cloudup.com/c0F1ztX8qu3 and then come back then this data disappears https://cloudup.com/cTFW32DxeRa
I am going back to second screen using router.go(-1) https://cloudup.com/cvpxk4GsIRx
The vue-router documentation https://router.vuejs.org/en/essentials/navigation.html says that “router.push method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.” and router.go(n) "This method takes a single integer as parameter that indicates by how many steps to go forwards or go backwards in the history stack"
However in my case, lifecycle hooks are called again when I go back to history stack. So does that mean when we come to previous page that component is created again and not popped from stack. I actually don’t want to refresh / reload the page on back button.
Toggle in loop?
I wish to toggle (show/hide) a list when clicking on a title, but cant get the following to work
I have this:
<!-- Title --> <div v-for="(subitem, index) in item" v-if="index === 0" @click="toggle(subitem)"> {{subitem.system_name}} - ({{item.length}}) </div> <!-- All title items that should expand on click "Title" --> <div v-if="subitem.clicked"> <p>{{subitem.system_name}}</p> </div>When clicking on the im triggering a toggle function called toggle, that sets a property on the item "clicked" to true or false (I should mention that this property does not already exist on the object, and I haven't got the possiblity add it, as we get the JSON from an API)
The toggle function is this:
toggle: function (data) { data.clicked = !data.clicked; },Now, when I do this above, I get an error saying: "Property or method "subitem" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option"
Im guessing I get this because the "clicked" property doesnt exist in the object... So how do I work around this? Can't see any real solution ?
Date Timestamp formatting in vuejs
I am building a SPA in vue js and I am getting date in a timestamp format i want it to be more human readable hence I tried using momentjs which didn't work for me. What is the best way to go in vue js