Software
Passing method event handling in Vue.js
I am very new to Vue.js and wrapping my head around method event handling.
What my function is doing is to read a barcode using web camera input and display its raw content.
The function works fine if I just render the raw content. However, if I try to transform the raw content to a more readable form. I am getting the following error:
TypeError: Cannot read property '1' of null when calling formatBarcode method.
I am pretty sure it's probably not even related to Vue.js in particular but a common JS problem.
html
<div id="scan"> <div class="row m-b-1"> <div class="col-sm-6"> <video id="preview"></video> <h5>Camera</h5> <ul> <li v-for="camera in cameras"> <span v-if="camera.id == activeCameraId" :title="formatName(camera.name)" class="active">{{ camera.name }}</span> </li> </ul> </div> <div class="col-sm-6"> <h5>Scans</h5> <transition-group name="scans" tag="ul"> <li v-for="scan in scans" :key="scan.date" :title="scan.content">{{ formatBarcode(scan.content) }}</li> </transition-group> </div> </div> </div>JS
var app = new Vue({ el: '#scan', data: { scanner: null, activeCameraId: null, cameras: [], scans: [] }, mounted: function() { var self = this; self.scanner = new Instascan.Scanner({ video: document.getElementById('preview'), scanPeriod: 5 }); self.scanner.addListener('scan', function(content) { self.scans.unshift({ date: +(Date.now()), content: content }); }); Instascan.Camera.getCameras().then(function(cameras) { self.cameras = cameras; if (cameras.length > 0) { self.activeCameraId = cameras[0].id; self.scanner.start(cameras[0]); } else { console.error('No cameras found.'); } }).catch(function(e) { console.error(e); }); }, methods: { formatBarcode: function(content) { const regex = /(01)(\d{14}|\d{0}})(21)(\d{10}|\d{0})/g; let m; while ((m = regex.exec(content)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } } return `Group1: (${m[1]}) ${m[2]} Group: (${m[3]}) ${m[4]}`; } } });This is the regex I'm trying to test https://regex101.com/r/SvCs5t/3
Working fiddle to test the regex transformation https://jsfiddle.net/o01474u2/
Walkthrough on Onsen -vue
How to load walkthrough component first among other component on the render method of vue?
import AppNavigator from './AppNavigator.vue'; import CustomToolbar from './partials/CustomToolbar.vue'; import WalkThrough from './pages/WalkThrough.vue'; Vue.use(VueOnsen); Vue.component('custom-toolbar', CustomToolbar); const app = new Vue({ el: '#app', render: h => h( AppNavigator //What I want to do is to load first walkthrough before loading the AppNavigator ) });Setting an active state with Vue JS and for loop
I have a list of strings in Vue, and I'm using v-for to list all of them in "list-group" with bootstrap. I want to set the "active" state on click on one of the items, but I can't find a way to ID a specific item on the list with the for loop.
HTML - <div class="list-group" id="ServersList"> <a href="#" class="list-group-item" v-for="Server in Servers">{{Server.text}}</a> </div>
VueJS - var ServersList = new Vue({ el: '#ServersList', data: { Servers: [ { text: '1' }, { text: '2' }, { text: '3' }, { text: '4' }, { text: '5' }, { text: '6' } })
Thanks!
Vue.js code doesn't work on a html without cdn
I'm new to Vue.js and i have a header html which doesn't have cdn link of Vue.js.
<nav class="navbar navbar-toggleable-md navbar-inverse"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <div class="containerNav"> <div class="row"> <div class="col-6"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="navbar-brand" href="#"><img src="images/logo.png" height="30"/></a> </li> <li class="nav-item active"> <a class="nav-link" href="index.html">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="login.html">TestPage</a> </li> </ul> </div> <div class="col-5" id="login-App"> <ul class="navbar-nav float-right"> <li class="nav-item"> <a class="nav-link" href="#">{{data.user}}</a> </li> <li class="nav-item"> <a class="nav-link" onclick="cleanLocalStorage()" href="login.html">Log out</a> </li> </ul> </div> </div> </div> </div> </nav>I load this header html with jquery document.ready function.
$(document).ready(function () { $(".footer").load("./footer.html"); $(".header").load("./header.html"); });Thererefore i cant show Vue.js variable on the page. Here is my Vue.js code
var loginApp = new Vue({ el: '#login-App', data: function () { return { data: {} } }, methods: { fetchData: function () { Vue.set(loginApp.data, 'user', JSON.parse(localStorage.getItem('user')).name); } } });If i use cdn link on header html, it works, but i prefer to use only on index page. Is there any trick for this situation? Should i use Vue.js CLI instead of cdn?
Get data from nested json and display using Vue-Multiselect
Basically what I want to achieve is GET data from server and display the data in the nested json to display in Multiselect, Vue-Multiselect
I'm able to get the objects from the nested json to display in multiselect, but I'm not sure how to customize it to only show the name.
So expected behaviour would be, only Sofa, Table and Chair should be shown in the multiselect:
Is there a way for me to only display like the picture above?
Thank you for your help!
vue js 2: Access props in mounted function
I have data props in child components. Inside child component on mounted function I need to get specific value from props and set select dropdown value. I am using vue-multiselect plugin which is working fine. Here is the code.
module.exports = { props: ["Subscriptions"] mounted: function () { let vm = this; Vue.nextTick(function () { // I want to access props here but it return 0 length array console.log(vm.$parent.Subscriptions); }); }, beforeUpdate() { let vm = this; console.log(vm.$parent.Subscriptions); }, // updated() { // let vm = this; // console.log(vm.$parent.Subscriptions); // } };Now only time I do get subscriptions is in beforeUpdate and updated function but this called each time there is a change in value which is not required. I only need to change it first time in order to set drop down initial value.
attaching css class to ID's in a vue app
First time SO poster here; I'm having some trouble with attaching a css class to an element with an ID; the way i'm doing it with classes is i have a click event on an HTML element that triggers a property to toggle state, and that property returns the new class, which works great.
When doing this and targeting an ID, i'm not too sure what i'm missing; I can get the click event to toggle state, but i'm not sure how to attach a class to that element ID. I've pasted the codepen below; thank you in advance.
<!-- testing ID binding--> <div id="excerciseID" @click="turnPink = !turnPink" :class="divClassesPink"></div> <br>TurnPink state: {{turnPink}} </div> new Vue({ el: '#app', data: { turnRed: false, turnPink: false }, computed: { divClassesRed: function(){ return { red: this.turnRed, blue: !this.turnRed } }, divClassesPink: function(){ return { pink: this.turnPink, blue: !this.turnPink } } }})Show loading property on Pageload with nuxt
I have a nuxt project that is working well. However on the loading of the page a async method is performed.
import charge from '~plugins/charge' export default { asyncData (context, callback) { const subscription = context.params.id; charge.getAll(subscription, function(result){ let data = result.data;; callback(null, data) }); } }My Problem is, that the page stays with until the async operation has been performed. How can i Show a loader until the function returns a result?
how can i set old input value on refresh in Vuejs
im using laravel and Vuejs
how can i set the input old value on refresh or back to the page in vue dynamic component
something like this :
value="{{ old('name') }}Vue & Webpack: Setting development and production variables
I'm using vue-cli to build my web app. My app uses an api in a number of places like so:
axios.post(API + '/sign-up', data).then(res => { // do stuff });The API variable is a constant containing the beginning of the address, e.g., https://example.com.
How would I detect whether this is a dev or prod build and set that variable accordingly? For now, I have a script tag in my index.html document and I am manually changing it for dev and prod:
<script>var API = 'https://example.com'</script>Is there a better way to handle this?
Why importing the Vue.js source works, but not the module?
The following HTML code
<!DOCTYPE html> <html lang="en"> <body> Greeting below: <div id="time"> {{greetings}} </div> <script src='bundle.js'></script> </body> </html>together with the entry.js file
// either the import or the require work Vue = require('./vue.js') //import Vue from './vue.js' new Vue({ el: "#time", data: { greetings: "hello world" } })and the webpack.config.js
module.exports = { entry: './entry.js', output: { filename: 'bundle.js' } }works fine (vue.js is locally downloaded from the site or a CDN).
I then tried to use the vue module installed via npm install vue --save-dev by changing entry.js to
import Vue from 'vue' new Vue({ el: "#time", data: { greetings: "hello world" } })This version does not work anymore: the whole <div> is not rendered (only Greeting below is displayed).
What should be done so that Vue.js can be used with webpack?
The Vue documentation mentions webpack a few times, but only in the context of components or production builds.
Should two-way binding work in vue when casting the value with the `.number` modifier?
This is what my HTML looks like:
<div v-for='(notUsingThis, index) in numbers'> <NumberWrap :index="index" :numbers="numbers" /> </div>
in NumberWrap.vue
<input type='number' number v-model.number='model' />I have a getter/setter there, I see the setter being called every time I change the value. However the second the field loses focus, it resets to nothing.
set model(val) { console.log('setting', val); this.numbers[this.index] = val; } get model() { console.log('getting', this.numbers[this.index]); return this.numbers[this.index]; }
If I log out my object in the console, I see it has been updated but the field is not showing it. If I remove the .number modifier it works as expected.
I know it seems indirect, but this is a simplification of how the code works.
Is there special handling I need to do myself when working with the casting? Is there anything that explicitly wrong with the way I use model get/set?
How to initialise components when using dynamic components
I have this code:
<div id="blocks"> <component v-for="block in blockList" :is="block.component" :id="block.uniqueId" :init-show-header="showHeaders" v-model="block.model" v-on:content-block-remove="removeBlock" :key="block.uniqueId"> </component> </div> addBlock(name) { let block = new Object() block.model = new Object() block.uniqueId = name + '-block-' + this.blockCount block.component = name + '-block' this.blockList.push(block) this.blockCount = this.blockCount + 1 }, <div id="buttons"> <button v-on:click="addBlock('taxonomy')" type="button" name="button" class="btn btn-primary btn-sm">Add Taxonomy</button> <button v-on:click="addBlock('text-input')" type="button" name="button" class="btn btn-primary btn-sm">Add Text Input</button> <button v-on:click="addBlock('header')" type="button" name="button" class="btn btn-primary btn-sm">Add Header</button> <!-- <button v-on:click="addBlock('text')" type="button" name="button" class="btn btn-primary btn-sm">Add Text</button> -->I have different types of components that have different kind of options stored in data object. I plan to save these options to the database upon saving the page where they are added and their settings adjusted. Each component type, its order on the page and components options are going to be saved in the database.
My question is, how do I initialise this page again after refreshing it and getting all the components and their options from the database? How would I get the options to each component when adding them in a loop on a mount event of the parent component where I load all components saved in the database and want to render them with the correct options?
What are my options?
Efficient ways to structure a main site + admin panel with vue-router?
What I am trying to accomplish is pretty straightforward. I want to have a set of main routes, e.g. '/', '/contact', '/blog', which all serve content from a database. At the same time, I need a set of routes which will be password-protected, e.g. '/admin/list', '/admin/add'.
My issue is that with the vue-cli and webpack combination, there is only one index.html, meaning that my admin panel and main site will be sharing the same meta tags, and CSS/JS files I include into index.html.
How would I go about serving a different .vue file to be used for div#app, depending on the current route? Apologies if this is something that's painfully easy to do. I'm just trying to figure out if there's a way to, more or less, 'host' two linked apps within the same routing engine.
This is a more 'visual' representation of what I'd do currently, but I feel like I'm missing something.
<app> <main> <main-nav/> <main-content/> <main-footer/> </main> <admin> <admin-nav/> <admin-content/> </admin> </app>Is there a way to do something like this with the Vue routing engine, where the HTML is very, very different for both 'apps'?
<main-app> <main-nav/> <main-content/> <main-footer/> </main-app> <admin-app> <admin-nav/> <admin-content/> </admin-app>Thanks for your time!
dropdowns and modals not working inside Vue components until I refresh the page
I am using Vue.js with Laravel 5.4 everything is working in the .blade.php files but not inside the .Vue files nothing happens when I click on a dropdown or a modal button. maybe I don't know what I'm doing but the weird thing that everything works fine when I refresh the page.
Any advice??
AspNet Core + Vue.js : User disappear in Controller
I created a new AspNet .Core + Vue.js app (using this template).
I use OAuth2 & the authentication systeme included in AspNet core to login (via Patreon), and when I disable the Vue app (delete the content of boot.ts), everything works, my User is correct, even in the Controllers.
But once the Vue.js is activated, black magic appear :
- The original login works
- The User is correct ONLY IN RAZOR PAGES
- The User is not correctly in my controllers (it's an anonymous user).
Code used in my razor page, which always works :
@if (User?.Identity?.IsAuthenticated ?? false) { <div id='app-root'>Loading...</div> <a class="btn btn-lg btn-danger" href="/logout">Sign out</a> } else { <h1>Welcome, anonymous</h1> <a class="btn btn-lg btn-success" href="/login">Sign in</a> }My Controller :
public IEnumerable<WeatherForecast> WeatherForecasts() { [...] var data = User; //User without data when the Vue app is activated [...] }My Vue.js routes :
const routes = [ { path: '/', component: require('./components/home/home.vue.html') }, { path: '/counter', component: require('./components/counter/counter.vue.html') }, { path: '/fetchdata', component: require('./components/fetchdata/fetchdata.vue.html') } ];And, to finish, samples of my Startup.cs :
app.UseCookieAuthentication(new CookieAuthenticationOptions() { AutomaticAuthenticate = true, AutomaticChallenge = true, LoginPath = new PathString("/login"), LogoutPath = new PathString("/logout") }); app.Map("/login", builder => { builder.Run(async context => { await context.Authentication.ChallengeAsync("Patreon", properties: new AuthenticationProperties() { RedirectUri = "/" }); }); }); app.Map("/logout", builder => { builder.Run(async context => { await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); context.Response.Redirect("/"); }); });I'm not used to handle authentication, and I'm a newbie in Vue.js, so I certainly made a mistake somewhere.
Anyone have an idea ?
Module not found: Error: Can't resolve 'avoriaz'
I'm new to Vue and am learning how to test it from this tutorial. I've reached the end of the tutorial but am getting a strange error on the last step of using avoriaz:
ERROR in ./test/unit/specs/list.spec.js Module not found: Error: Can't resolve 'avoriaz' in '/Users/harishramachandran/tmp/Dropbox/Sites/tmp/vuejs- testing/test/unit/specs' @ ./test/unit/specs/list.spec.js 3:15-33 @ ./test/unit/specs \.spec$ @ ./test/unit/index.jsHere's the relevant code in my test file:
import { mount } from 'avoriaz'; import List from '@/components/List'; import Vue from 'vue'; ...And my package.json file:
... }, "dependencies": { "vue": "^2.3.3", "vue-router": "^2.6.0" }, "devDependencies": { "autoprefixer": "^7.1.2", "avoriaz": "^2.6.3", ...I tried removing my node_modules directory and package-lock.json and reinstalling everything with npm install to no avail.
Any ideas as to what could be causing this, and how to resolve it?
Fetch caching response - no-cache headers not working as expected
I've been doing the random quote machine project for freecodecamp and I can't seem to stop the response from the api being cached.
I've tried various answers:
- fetch(), how do you make a non-cached request?
- https://forum.freecodecamp.org/t/apis-and-the-random-quote-machine-not-even-sure-what-to-ask/65982/13
I thought I had it at one point:
fetch(this.url, {cache: 'no-cache'}) .then(res => res.json())... but I was just disabling the cache in developer tools.
Please help. :-D.
Here is where i've been trying to make it work: https://codepen.io/JonathanDWood/pen/gRNNKx
[Vue warn]: Error in render function: "TypeError: Cannot read property 'matched' of undefined"
am trying to route using two routers for two pages, main.js and profile.js and two init files main and profile
//for main pages import Vue from 'vue'; import App from './App'; import MainRouter from './router/main.js'; Vue.config.productionTip = false /* eslint-disable no-new */ /* vue init for main pages with MainRouter */ new Vue({ el: '#main-app', MainRouter, template: '<App/>', components: { App } })
import Vue from 'vue'; import App from './App'; import ProfileRouter from './router/profile.js' Vue.config.productionTip = false /* eslint-disable no-new */ /* vue init for profile pages with profile pages router */ new Vue({ el: '#profile-app', ProfileRouter, template: '<App/>', components: { App } })
routers are..
/* Router for main pages */ import Vue from 'vue' import Router from 'vue-router' /* pages */ import Meeting from '@/components/pages/meeting' import Feeds from '@/components/pages/feeds' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Feeds', component: Feeds }, { path: '/meeting', name: 'Meeting', component: Meeting }, { path: '/activities', name: 'Activities History', component: Activities }, { path: '/add_member', name: 'Add Member', component: Add_Member } ] })
profile.js
/* Router for profile related pages */ import Vue from 'vue' import Router from 'vue-router' /* pages */ import Activities from '@/components/pages/activities_history' import Change_Password from '@/components/pages/change_password' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Edit Profile', component: Edit_Profile }, { path: '/activities', name: 'Activities History', component: Activities } ] })
ill include more codes if needed... it was working fine while there was only one router. can u troubleshoot issue. Thanks in advance
Vuejs code change dose not appear in website
I developed laravel 5.4 project, and then hosted it, and I setup nodejs and other packages on server, but when edit in vuejs code, the change does not appear in the website. I also run "npm run dev" but it shows error for me this is error:
npm ERR! code ELIFECYCLE npm ERR! errno 126 npm ERR! @ development: cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules config=node_modules/laravel-mix/setup/webpack.config.js npm ERR! Exit status 126 npm ERR! npm ERR! Failed at the @ development script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.