Software
How to stop router from a component?
There is a component
It takes some action and a person should not leave without having saving
There is method beforeDestroy()
This works fine, but I do not understand how to stop transition.
Rather, the link changes, but the component has not yet deleted.
How to apply Vue.js scoped styles to components loaded via view-router?
How can I apply Vue.js scoped styles to components loaded via <view-router>.
Here is my code:
<template> <div id="admin"> <router-view></router-view> </div> </template> <style lang="scss" scoped> #admin { .actions { display: none; span { cursor: pointer; } } } </style>When I visit the /posts a component named Posts will be loaded, inside this component I have a
<div class="actions"> some content </div>The problem is that the style defined in #admin is not applied to .action element. When not scoped, this works fine. The problem come when the #admin component styling is scoped.
Is there any way to do that while keeping the .actions style inside the admin component scoped style tag?
How to implement pouchdb in cordova with an app packaged by webpack?
I would like to ask if anyone knows how to integrate pouchdb in a cordova app? I have already created a To Do app in webpack/vue-cli and have successful run them in the browser environment however when I try to package the app for mobile development, it seems that the database I initially used (pouchdb) is not working anymore. I have tried googling every topic I know just to implement this logic but to no avail.
To give you an idea how I developed my app here are the steps:
- Used vue-cli to create a boilerplate for the app. I have used Vuetify, Vuex, and Vue-router, PouchDB inside the app.
- After developing the app and successfully run through the browser(with database connection working), I package the app using npm run build of webpack to create a browser compatible distribution.
- Then I went to create a cordova project using the cordova cli, and then I went to its www folder and replaced the index.html with my webpack app.
- Then I ran the webpack/cordova app, the only difference is that is does not load any data from my pouchdb database anymore even if I run cordova run browser command.
Thank you
How to Import Specific Files Inside Node_Modules
Okay, so I am using webpack-simple for VueJS. I installed a theme called AdminLTE. I tried to import the bootstrap files inside it via the code below. When I run npm run build, the app searches inside the src folder but AdminLTE is inside node_modules folder.
Should I import just those files that I need, or should I import the whole folder. And How do I properly import those files?
My main.js file
import Vue from 'vue' import App from './App.vue' // import BootstrapCSS from 'admin-lte/bootstrap/bootstrap.min.css' // import BootstrapCSSTheme from 'admin-lte/bootstrap/bootstrap-theme.min.css' import 'admin-lte/bootstrap/bootstrap.min.css' import 'admin-lte/bootstrap/bootstrap-theme.min.css' new Vue({ el: '#app', render: h => h(App) })My Webpack Config
var path = require('path') var webpack = require('webpack') module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, './dist'), publicPath: './dist/', filename: 'build.js' }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { } // other vue-loader options go here } }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.css$/, use: ['style-loader','css-loader'] }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } } ] }, resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js' } }, devServer: { historyApiFallback: true, noInfo: true }, performance: { hints: false }, devtool: '#eval-source-map' } if (process.env.NODE_ENV === 'production') { module.exports.devtool = '#source-map' // http://vue-loader.vuejs.org/en/workflow/production.html module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new webpack.optimize.UglifyJsPlugin({ sourceMap: true, compress: { warnings: false } }), new webpack.LoaderOptionsPlugin({ minimize: true }) ]) }Import with Babel and Webpack loader in Vue.js
I cannot get past this linting error. I feel like I'm tried everything. Can someone help me out?
ERROR in ./~/babel-loader/lib!./~/vue-loader/lib/selector.js?type=script&index=0!./src/components/Register.vue Module not found: Error: Can't resolve '@/services/AuthenticationService' in 'C:\Users\Sean\Desktop\tabtracker\tabtracker\client\src\components' @ ./~/babel-loader/lib!./~/vue-loader/lib/selector.js?type=script&index=0!./src/components/Register.vue 25:0-69 @ ./src/components/Register.vue @ ./src/router/index.js @ ./src/main.js @ multi ./build/dev-client ./src/main.jsSo basically I searched through the web looking for an answer and it seems to be a common enough problem. I checked out the same issue on the official vue forum and was not able to have a successful build. I read through github issues like crazy and still feel no closer.
I've tried rolling babel back and adding a plugin but i'm afraid I'm not adding them to the correct config files, there's so many.
How to get rid of infinite update loop warning in a recursive component loop in vue?
I am using vue-router and want to generate a menu from its items (router obj) at the same time. I am trying to do that using a recursive components. But I am stuck at a infinite loop warning although I have a ending condition. Actually my main problem here occurs when I want to use/modify a level counter in the recursive component that counts the corresponding level. I get this: [Vue warn]: You may have an infinite update loop in a component render function.
This is what I've got:
In order to keep it simple I've reduced the routes and other parts to show just the needed parts for this question.
// routes.js export let routers = [ { name: 'Products', path: 'products', children: [ { name: 'Products2', path: 'products', children: [ { name: 'Products3', path: 'products' } ] } ] }, { name: 'Tables', path: 'simple_tables', }, { name: 'Other Menu', path: 'other_menu', }];This is the parent of the recursive component. Instead placing the level data to the child component, I placed it to the parent (left-side.vue) so that it can work without being reset on each recursion. I used custom events for communicating between parent and child. Thus I can pass and modify it without a problem.
// left-side.vue <template> <aside class="left-side sidebar-offcanvas"> <section class="sidebar"> <div id="menu" role="navigation"> <navigation-cmp :routes="routes" :level="level" @levelup="levelup()" @leveldown="leveldown()"></navigation-cmp> </div> </section> </aside> </template> <script> import navigationCmp from './navigationCmp'; import {routers} from '../../router/routers'; export default { name: "left-side", data() { return { level: 0 } }, computed: { routes(){ return routers; } }, methods: { levelup(){ this.level++; }, leveldown(){ this.level--; } }, components: { navigationCmp, }, } </script>Here is the recurring part. Each time it gets into recursion it emits level up to the parent to increase and emits level down to decrease the level variable. And it should actually stop if there is no more children to prevent infinite loop.
<template> <ul class="navigation"> <template v-for="route in routes"> <li> <template v-if="!route.children"> {{ route.name }} </template> <template v-else-if="route.children&&route.children.length>0"> {{ route.name }} <template v-for="child in route.children"> {{ levelup() }} {{ child.name }} <navigation-cmp v-if='child.children&&child.children.length>0' :routes="[child]"></navigation-cmp> {{ leveldown() }} </template> </template> </li> </template> </ul> </template> <script> export default { name: 'navigation-cmp', props: { routes: Array, level: Number }, methods: { levelup(){ this.$emit('levelup'); }, leveldown(){ this.$emit('leveldown'); } } } </script>Obviously I am doing something wrong here. I am stuck and don't know how I could solve this. What am I doing wrong? Any advise or guidance would really be appreciated.
Google map is not showing in vue.js
I have bulit an app based on Vue.js using Monaca,Cordova and onsenUI. I want to show my location using Google map in my page. To implement this I have used a npm package vue2-google-maps but it does not show anything.
The codes I have used are from the official documentation of the package. They are given below:
<template> <v-ons-page> <custom-toolbar>Page 1</custom-toolbar> <div> <gmap-map :center="center" :zoom="7" style="width: 500px; height: 300px" > <gmap-marker :key="index" v-for="(m, index) in markers" :position="m.position" :clickable="true" :draggable="true" @click="center=m.position" ></gmap-marker> </gmap-map> </div> </v-ons-page> </template> <script> import * as VueGoogleMaps from 'vue2-google-maps'; import Vue from 'vue'; Vue.use(VueGoogleMaps, { load: { key: 'AIzaSyDX3SEHwFUY-k_Jp7YMp0-uTvo7up-paXM', v: '3.26', // libraries: 'places', //// If you need to use place input } }); export default { data () { return { center: {lat: 10.0, lng: 10.0}, markers: [{ position: {lat: 10.0, lng: 10.0} }, { position: {lat: 11.0, lng: 11.0} }] } }, props: ['pageStack'], components: { customToolbar } }; </script>Error while installing vue-cli
When i run npm install -g vue-cli , it continuously throws this error message:
npm ERR! path C:\Users\End User\AppData\Roaming\npm\node_modules\vue-cli\node_modules\nan\package.json npm ERR! code EPERM npm ERR! errno -4048 npm ERR! syscall unlink npm ERR! Error: EPERM: operation not permitted, unlink 'C:\Users\End User\AppData\Roaming\npm\node_modules\vue-cli\node_modules\nan\package.json' npm ERR! at Error (native) npm ERR! { Error: EPERM: operation not permitted, unlink 'C:\Users\End User\AppData\Roaming\npm\node_modules\vue-cli\node_modules\nan\package.json' npm ERR! at Error (native) npm ERR! stack: 'Error: EPERM: operation not permitted, unlink \'C:\Users\End User\AppData\Roaming\npm\node_modules\vue-cli\node_modules\nan\package.json\'\n at Error (native)', npm ERR! errno: -4048, npm ERR! code: 'EPERM', npm ERR! syscall: 'unlink', npm ERR! path: 'C:\Users\End User\AppData\Roaming\npm\node_modules\vue-cli\node_modules\nan\package.json' } npm ERR! npm ERR! Please try running this command again as root/Administrator.
npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\End User\AppData\Roaming\npm-cache_logs\2017-09-10T06_15_03_457Z-debug.log
I tried all the possible solutions found online :
running from windows cmd with administrator access,
npm cache clean
closed my text editor
restarted my PC
Please do help me solve this issue.
CSS/JS to imitate multiple mobile app screens: left-to-right orientation, one-at-a-time behavior
I am working on a Flask / Vue.js web app that I want to have work well with both laptop and mobile browsers. The layout I've chosen is to have a series of mobile-screen-shaped areas that are oriented in a left-to-right fashion when viewed on a laptop browser. Currently when viewed on mobile those mobile-screen-sized areas get shifted into a top-to-bottom orientation, and the user can scroll the screen up and down to go through them all.
What I'd like to do is to have the mobile CSS instead simulate a mobile app by having those cards(?) oriented left-to-right (like the laptop view), and have a swipe shift each one into view or out of view, but always snapping to a single card at a time, rather than displaying 1/4th of the first card and 3/4ths of the second card (for example).
Custom event in Vuejs2
I'm not understanding the Custom Event in Vuejs2.
I have a component named as user-navbar witch contains a dropdown menu, when change I execute this method:
handleCurrentServerChange: function(name, zoneid, currency_name) { /* Code omitted */ this.$emit('server-changed', { serverznid: zoneid }); },Wich emit an event called server-changed and I want to listen to this event in another component accounts-linked.
<accounts-linked inline-template :server_data="server_data" @server-changed="handleServer">When the event is emitted I should call the method handleServer. But isn't working. This is the method:
handleNewMessage: function(value) { alert(value); }I got few errors
[Vue warn]: Property or method "handleServer" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. [Vue warn]: Invalid handler for event "server-changed": got undefinedWhat am I doing wrong?
Search Bar Filter Using Vue with child component
I am creating a dynamic search bar that will filter a sidebar full of names based on user input. However, I am having trouble temporarily hiding and showing data based on the search bar's value on keyup. What is the best way to achieve this the "Vue way"?
On keyup, I want to filter through all of the this.people data and only show names that contain the value of the search input.
Below is what my code looks like
//Javascript Vue.component('sidebar',{ props: ['people', 'tables'], data: () => { return { fullName: '' } }, computed: { computed() { return [this.people, this.tables].join() } }, template: ` <div id="sidebarContain" v-if="this.people"> <input id="sidebar-search" type="text" placeholder="Search..." @keydown="searchQuery"> <select id="sidebar-select" @change="sidebarChanged"> <option value="AZ">A-Z</option> <option value="ZA">Z-A</option> <option value="notAtTable">No Table</option> <option value="Dean's Guest">Dean's Guest</option> <option value="BOO | VIP">BOO | VIP</option> </select> <div v-for="person in people" :class="[{'checked-in': isCheckedIn(person)}, 'person']" :id="person.id" :style="calcRegColor(person)"> <span v-if="person.table_name">{{person.first_name + ' ' + person.last_name + ' - ' + person.table_name}}</span> <span v-else>{{person.first_name + ' ' + person.last_name}}</span> </div> </div> `, methods: { isCheckedIn(person) { return person.reg_scan == null ? true : false; }, isHidden(person) { console.log("here"); }, calcRegColor(person) { switch(person.registration_type) { case "Dean's Guest" : return { color: 'purple' } break; case "BOO | VIP" : return { color: 'brown' } break; case "Student" : return { color: 'green' } break; case "Faculty": case "Staff": return { color: 'blue' } break; case "Alumni Club Leader": return { color: 'gold' } break; case "Table Guest" : return { color: 'pink' } break; default: return { color: 'black' } } } }, watch: { computed() { console.log("People and Tables Available"); } } }); //HTML <div id="app"> <sidebar :people="people" :tables="tables"></sidebar> </div>What does attribute "for" a label does (Vue.js)
I am playing around with this simple example trying to understand what attribute "for" does and can't seem to figure it out. I tried changing the value of "for" attribute and even removing it completely and it still works just fine (at least on the appearance). I would appreciate if someone can give me an explanation.
I just started to study Vue.js so this might be a very simple answer.Best practice to make multiple Vuejs javascript files work together
I can't find much information on the web with explanation on how to use multiple vuejs instances and make them work together.
Please, can someone show me his code style on how to do that?
I have a main /resources/assets/js/app.js:
Vue.component('google-maps', require('./components/Gmaps.vue')); export const App = window.App = new Vue({ el: '#app', mounted(){ // Listen for an event socket.on('alarm-channel:App\\Events\\AlarmCreated', ({data}) => { return this.alarmCreated(data.alarm); }); }, data: { users: [], alarms: [] // #01 - should be in Alarms.js }, methods: { /* Newly registered alarm */ alarmCreated(alarm){ this.alarms.push(alarm); // #01 - should be in Alarms.js } } });How can I call a same new Vue() inside /resources/assets/js/alarms.js to make it work together ?:
Rails data confirm with vue.js
I am trying to do away with jQuery in my Rails 5.1 app and move to use only Vue.js.
I have three questions in this regard:
- Is this a sensible thing to do? Can Vue.js fully replace jQuery or should they co-exist?
- How would I replace all the data-confirm niceties that Rails provides by default and convert them to their Vue equivalent?
- How would I localize strings such as the data-confirm strings?
Just trying to get an idea of whether this is feasible. Thanks!
How to use Visual Studio 2017 and Vue single file components
I use Visual Studio 2017 and have a fair amount of ASPNET Core invested. That being said, I do like using Vue.js 2.0 for some UI workflow stuff on certain pages. I can't seem to find a suitable, and lightweight, way to compile a .vue file (single file component) and end up with a clean output .js and .css file. I've used npm, vue-cli, and webpack, but the resulting .js file for my single file component contains a bunch of other SPA, export, etc. overhead.
Isn't there just an easy way to use VS such that when a .vue file was saved, it would auto-generate the .js and .css file (I use LESS css) cleanly?
I guess the main reason I want to use a .vue file is to get syntax highlighting on the HTML as well as having my all in a common location.
Any thoughts? I would hope you could have configured VS to do a vue-cli (or some other tool) compile upon save like it does with .less files for css, and create a new .js and .css file. Something tells me webpack could do this with a custom config, but no one appears able to articulate exactly how to do this in detail.
How to attach events in vue directives?
I need to attach functions to element using directives. I want to do it with Vue method $on, but it's not working. When I do it with addEventListener, event.target.value gives me unchanged value after first input, second works correctly. How to fix it?
Example: jsfiddle.net rjeu8Lc1/1/
Vuejs routing working only partially.
My App works just fine, if I put routes without childrens (nesting) but I tried to nest it just now and converted my routes to this: in routes.js
import alphabetsPage from './components/views/pages/alphabets.vue' import dictionaryPage from './components/views/pages/dictionary.vue' import numbersPage from './components/views/pages/numbers.vue' import LayoutView from './components/views/Layout.vue' const routes = [{ path: '/', name: 'Home', component: LayoutView, children: [{ path: 'basic', name: 'Basic', component: alphabetsPage, children: [{ path: 'alphabets', name: 'Aphabets', component: alphabetsPage }, { path: 'numbers', name: 'Numbers', component: numbersPage }] }] }] export default routesIf I go to / or click on route <router-link to="/basic/alphabets" tag="li"><a>numbers</a></router-link> I can see the alphabetsPage component, however if I go click on <router-link to="/basic/numbers" tag="li"><a>numbers</a></router-link> the route doesn't work. I have a numbersPage componet working.
This must be from the routes, because, if I don't use children and just define the path in routes as /basic/numbers or /basic/alphabets it works.
Vue js interpolation values sum
There exist any way in Vue js to make a sum between two interpolation values inside an html tag?
ex:
value1= 5 value2= 3
<span> {{value1}} + {{value2}}</span>So I would like to know if its posible to obtain a third value rendered on the span tag adding the two values.
Vue.js (2.0) unit test issue
I am trying to perform unit test on vuex actions, using Mocha and Sinon
here is my action.spec.js
import actions from '@/vuex/actions' import * as types from '@/vuex/mutation_types' describe('actions.js', () => { var server, store, lists, successPut, successPost, successDelete successDelete = {'delete': true} successPost = {'post': true} successPut = {'put': true} beforeEach(() => { // mock shopping lists lists = [{ id: '1', title: 'Groceries' }, { id: '2', title: 'Clothes' }] // mock store commit and dispatch methods store = { commit: (method, data) => {}, dispatch: () => { return Promise.resolve() }, state: { shoppinglists: lists } } sinon.stub(store, 'commit') // mock server server = sinon.fakeServer.create() server.respondWith('GET', /shoppinglists/, xhr => { xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(lists)) }) server.respondWith('POST', /shoppinglists/, xhr => { xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(successPost)) }) server.respondWith('PUT', /shoppinglists/, xhr => { xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(successPut)) }) server.respondWith('DELETE', /shoppinglists/, xhr => { xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(successDelete)) }) server.autoRespond = true }) afterEach(() => { // restore stubs and server mock store.commit.restore() server.restore() }) describe('populateShoppingLists', () => { it('should call commit method with POPULATE_SHOPPING_LIST string parameter', done => { actions.populateShoppingLists(store).then(() => { expect(store.commit).to.have.been.calledWith(types.POPULATE_SHOPPING_LISTS, lists) done() }).catch(done) }) }) describe('changeTitle', () => { it('should call commit method with CHANGE_TITLE string', (done) => { let title = 'new title' actions.changeTitle(store, {title: title, id: '1'}).then(() => { expect(store.commit).to.have.been.calledWith(types.CHANGE_TITLE, {title: title, id: '1'}) done() }).catch(done) }) }) describe('updateList', () => { it('should return successful PUT response', (done) => { actions.updateList(store, '1').then((data) => { expect(data.data).to.eql(successPut) done() }).catch(done) }) }) describe('createShoppingList', () => { it('should return successful POST response', (done) => { let newList = { title: 'new list', id: '3' } actions.createShoppingList(store, newList).then((testResponse) => { console.log('testResponse: ', testResponse) expect(testResponse.body).to.eql(successPost) done() }).catch(done) }) }) })here is my action.js
import { CHANGE_TITLE, POPULATE_SHOPPING_LISTS } from './mutation_types' import api from '../api' import getters from './getters' export default { populateShoppingLists: ({ commit }) => { return api.fetchShoppingLists().then(response => { commit(POPULATE_SHOPPING_LISTS, response.data) }) }, changeTitle: (store, data) => { store.commit(CHANGE_TITLE, data) return store.dispatch('updateList', data.id) }, updateList: (store, id) => { let shoppingList = getters.getListById(store.state, id) return api.updateShoppingList(shoppingList) }, createShoppingList: (store, shoppinglist) => { return api.addNewShoppingList(shoppinglist).then((actionResponse) => { console.log('actionResponse: ', actionResponse) store.dispatch('populateShoppingLists') }) }, }running my unit tests , I have an issue with the createShoppingList test
console.log
actions.js populateShoppingLists ✓ should call commit method with POPULATE_SHOPPING_LIST string parameter changeTitle ✓ should call commit method with CHANGE_TITLE string updateList ✓ should return successful PUT response LOG LOG: 'actionResponse: ', Response{url: 'http://localhost:3000/shoppinglists', ok: true, status: 200, statusText: 'OK', headers: Headers{map: Object{Content-Type: ...}}, body: Object{post: true}, bodyText: '{"post":true}'} LOG LOG: 'testResponse: ', undefined createShoppingList ✗ should return successful POST response undefined is not an object (evaluating 'testResponse.body') webpack:///test/unit/specs/vuex/actions.spec.js:90:28 <- index.js:15508:28 webpack:///~/vue-resource/dist/vue-resource.es2015.js:151:0 <- index.js:17984:52 webpack:///~/vue/dist/vue.esm.js:701:0 <- index.js:3198:18 nextTickHandler@webpack:///~/vue/dist/vue.esm.js:648:0 <- index.js:3145:16whicj indicates that in the createShoppingList action, the reponse is not sent back on the return, so expect(testResponse.body).to.eql(successPost) is not true...
what's wrong with my Promise handling in this case ?
thanks for feedback
Vue js dynamic data component
I'm passing some dynamic data from a parent component to a child component using props . I'm displaying the child component and the script. So I would like to know how I can add myColor prop to total value and show it an render the result in a final value. I'm using Vue 2 and webpack.
<v-layout> <v-layout> <v-flex > <h3 >Total price:</h3> </v-flex> </v-layout> <v-layout> <v-flex <v-subheader> {{total}} {{myColor}} €</v-subheader> </v-flex> </v-layout> </v-layout> <script> export default { props: ['myColor'], data: () => ({ checked1: '', showCart: false, colors: [{ id: 1, name: "white", price: 2, checked: '', }, { id: 2, name: "black", price: 2.0, checked: '', }, { id: 3, name: "Grey", price: 2.25, checked: '', }, { id: 4, name: "Blue", price: 1.6, checked: '', }, { id: 5, name: "Red", price: 2.5, checked: '', }, { id: 6, name: "Yellow", price: 2.75, checked: '', }], }), computed: { total: function() { var total = 0; for (var i = 0; i < this.colors.length; i++) { if (this.colors[i].checked) { total += this.colors[i].price; } } return total; }, }, } </script>