Vuejs

Subscribe to Vuejs feed
most recent 30 from stackoverflow.com 2017-09-14T21:10:11Z
Updated: 7 years 1 week ago

VueRouter route should select first child by default

Tue, 2017-07-25 12:49

Hi everyone i'm using Vue-Router 2.5.3 and i have the following Route structure.

path: "/admin", component: require("./views/layouts/MasterLayout.vue"), meta: { requiresAuth: true }, children: [ { path: 'dashboard', component: require("./views/Dashboard.vue"), alias: "/", name: "dashboard" }, { path: 'upload', component: require("./views/Upload.vue"), name: "upload", redirect: {name: 'upload.photo'}, children: [ { path: 'photo', component: require("./components/Uploaders/ImagesUploader.vue"), name: "upload.photo", props: { selected: true, successEndpoint: "/api/v1/upload/complete", uploadEndpoint: "/api/v1/upload" } }, { path: 'video', component: require("./components/Uploaders/VideoUploader.vue"), name: "upload.video", props: { selected: true, successEndpoint: "/api/v1/upload/complete", uploadEndpoint: "/api/v1/upload" } } ] },

And i have an issue with this configuration, whenever i navigate to "admin/upload" it shows a blank page, i want it to show "admin/upload/photo" by default even if my users navigate to "admin/upload" how can i acheive this in Vue Router?

I've already tried defining aliases in both "upload" and in the child routes and nothing happened, then i tried to define the redirect key in the "upload" parent route as well and again blank page...

I don't quite get what im going wrong, is it the fact that my structure has two levels of nesting? But if that's a problem how do i define these routes using only one level of nesting?

Categories: Software

setTimeout() not working called from vueJS method

Tue, 2017-07-25 12:47

I am trying to allow a user to reset or shutdown a given server from an app. Im working on the interface right now, and want to give the user messages as to what is happening. I display a message defined in my data object to indicate the action taken. I thene use setTimeout to switch a resetting.... message with a reset message. See the following method.

systemReset: function(){ this.message = this.server + ': Resetting'; setTimeout(function(){ this.message = this.server + ': Reset'; }, 2000); }

In my browser I can trigger this message and my message of "Resetting" displays, but the following "Reset" message is never output. Do I have any formatting errors?

To put this method in context here is my entire component.

<template> <div> <p>{{message}}</p> <button @click="systemReset">Reset Server</button> <button @click="systemPowerDown">Poweroff Server</button> </div> </template> <script type="text/javascript"> export default{ data: function(){ return{ message: '' } }, methods: { systemPowerDown: function(){ this.message = this.server + ': Server Down'; }, systemReset: function(){ this.message = this.server + ': Resetting'; setTimeout(function(){ this.message = this.server + ': Reset'; }, 2000); } }, props: ['server'] } </script> Am I missing something obvious? Or is there some vue limitation I am unaware of?
Categories: Software

Vue js --The dependency was not found : ts-loader not compiling

Tue, 2017-07-25 12:43

The scenario: There is a library with generic vue js components that will be used by several projects and not using typscript. The library is a seperate project and have seperate webpack settings.

This library is being consumed inside my project as a git sub module atm and my project( I will call as main project here) is using typscript and ts-loader to compile the js and ts .

Can any one guide me wether it is problem because one project is using ts and other not? something with the module config? I can access other folder and files outside of main project src directory, but not the components inside of this library? If any one has a better way of doing the, will be thankful for advise!

/** webpack.base.conf (from main project **/ module: { { test: /\.ts$/, loader: 'ts-loader', include: [resolve('src'), resolve('test')], exclude: '/node_modules', options: { appendTsSuffixTo: [/\.vue$/] } } }

Inside of my main projects component I am trying to import one the components from the library, which I am unable to as ts-loader tells the dependency was not found

/** Header.vue (main project)**/ <template> </template> <script lang="ts"> // lib in root same as src folder for main project import GenericComponentFromLib from 'lib/generic-components/src/components/GenericButton' @Components({ components: { GenericButton } }) /** tsconfig.json (main project) **/ { "compilerOptions": { "target": "es5", "lib": ["es5", "es2015.promise","es2017.object", "dom"], "module": "commonjs", "rootDir": ".", "moduleResolution": "node", "allowSyntheticDefaultImports": true, "experimentalDecorators": true }, "exclude": [ "node_modules" ] }
Categories: Software

TypeScript and the this keyword (SharePoint Framework and Vue)

Tue, 2017-07-25 11:28

I'm working on a SharePoint Framework web part and using Vue.js.

Given this snippet:

export default class MyWorkspaceTestWebPart extends BaseClientSideWebPart<IMyWorkspaceTestWebPartProps> { public uol_app; public render(): void { this.domElement.innerHTML = "some markup" this.uol_app = new Vue({ el: `#vueapp-${this.context.instanceId}`, data: { announcements: [], numOfAnnouncements: 4 }, computed: { announcementsTrimmed: function() { return this.uol_app.announcements.splice(0, this.uol_app.numOfAnnouncements) } } }) } }

On that last return statement, how can I get to the announcements and numOfAnnouncements Vue data properties?

I have tried:

return this.uol_app.announcements.splice(0, this.uol_app.numOfAnnouncements) return this.uol_app.data.announcements.splice(0, this.uol_app.data.numOfAnnouncements) return this.data.announcements.splice(0, this.data.numOfAnnouncements) return this.announcements.splice(0, this.numOfAnnouncements) return uol_app.announcements.splice(0, this.numOfAnnouncements)
Categories: Software

How to publish a library of Vue.js components?

Tue, 2017-07-25 11:13

I am working on a project containing a Vuex module and an abstract components that users can extend from.

I would love to publish this on NPM to clean up my codebase and pull this away from my project as a solid well tested module. I have specified the main file in package.json to load an index which imports everything I want to expose:

https://github.com/stephan-v/vue-search-filters/

The index contains this at the moment:

import AbstractFilter from './src/components/filters/abstract/AbstractFilter.vue'; import Search from './src/store/modules/search'; module.exports = { AbstractFilter, Search };

For this to work I need to transpile this since a babel compiler normally won't transpile files imported from node_modules(Correct me if I am wrong here). Besides that I would probably be a good idea to do this so it can be used by different systems.

How do I transpile only the files that I need though with Webpack? Do I have to create a separate config for this?

What does a config like that look like? I know the vue-cli has a build command for one single file component but this is a bit different.

Any tips or suggestions on how to transpile something like this are welcome.

Categories: Software

How to combine max-width, min-width in matchMedia query?

Tue, 2017-07-25 10:20

I am working with the matchMedia API to determine viewports within javascript, so I can minimize the amount of dom manipulation taking place.

Instead of using display: none everywhere I determine if elements are inserted into the DOM or not with a v-if directive from Vue.

I have set it up like this:

resize() { this.mobile = window.matchMedia('(max-width: 767px)').matches; this.tablet = window.matchMedia('(max-width: 767px)').matches; this.desktop = window.matchMedia('(min-width: 992px)').matches; }

The mobile matchmedia query is fine but how do I determine exactly what is tablet size? I am wondering if I can combine max-width and min-width values within the matchMedia query.

Of course I could do something like this:

resize() { this.mobile = window.matchMedia('(max-width: 767px)').matches; this.desktop = window.matchMedia('(min-width: 992px)').matches; this.tablet = !this.mobile && !this.desktop; }

I am wondering is this is properly set up like this though.

Categories: Software

Vue Render JQuery Plugin Upon v-if Set to True On Ajax Call

Tue, 2017-07-25 10:01

I have a checkbox that is being styled by iCheck, a JQuery plugin. The checkbox has a v-if directive, which will be set to true by a JQuery Post request.

function initializeICheck() { $('input').iCheck({ checkboxClass: 'icheckbox_square-blue', radioClass: 'iradio_square-blue', increaseArea: '20%' // optional }); } var login = new Vue({ el: '#vLogin', data: { showcheckbox: false, }, methods: { validateLogin: function() { $.post("validate", function(data, textStatus, xhr) { }).done(function(response) { login.showcheckbox = true; initializeICheck(); }); } } });

However, when the validateLogin method is being called, the checkbox appears, but the call to function doesn't seem to work.

Any idea how do I properly render the checkbox styling?

Categories: Software

vue js nested array load to table

Tue, 2017-07-25 09:48

in vue js how to load nested array to a html table. when I use v-for inside v-for it qives an error Property or method "key" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

[ { jobtype_id:"1", jobtype_code:"L001", jobtype_name:"Labour", jobtype_order:"1", jobtype_comment:"1", jobs:[ { jobinvoicedtlid:"1", JobInvNo:"JBIN0016", JobCardNo:"", JobType:"1", JobCode:null, JobDescription:"Wheel alignment", JobQty:"2", JobPrice:"800.00", JobTotalAmount:"1600.00", JobDiscount:"0.00", JobNetAmount:"1600.00", JobDiscountType:"1", JobinvoiceTimestamp:"2147483647", Description:"Labour" }, { jobinvoicedtlid:"2", JobInvNo:"JBIN0016", JobCardNo:"", JobType:"1", JobCode:null, JobDescription:"Full Service", JobQty:"4", JobPrice:"250.00", JobTotalAmount:"1000.00", JobDiscount:"0.00", JobNetAmount:"1000.00", JobDiscountType:"1", JobinvoiceTimestamp:"2147483647", Description:"Labour" } ] }, { jobtype_id:"2", jobtype_code:"S002", jobtype_name:"Parts Outside", jobtype_order:"3", jobtype_comment:null, jobs:[ { jobinvoicedtlid:"3", JobInvNo:"JBIN0016", JobCardNo:"", JobType:"2", JobCode:null, JobDescription:"Oil Change", JobQty:"5", JobPrice:"500.00", JobTotalAmount:"2500.00", JobDiscount:"0.00", JobNetAmount:"2500.00", JobDiscountType:"1", JobinvoiceTimestamp:"2147483647", Description:"Parts Outside" } ] } ] <tbody> <tr v-for="item,key in printdata"> <td colspan='6'> <b>{{item.jobtype_name}}</b></td> <table border="1"> <tr v-for="itm in printdata.jobs"> <td>itm.JobDescription</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </table> </tr> </tbody>

Categories: Software

VueJS dynamic v-model value

Tue, 2017-07-25 09:16

I want to set v-model to a value dictated by the value in my v-for loop. here's my code:

<tr v-for="campaign in _campaigns"> <el-switch v-model="campaign.enabled"></el-switch> </tr>

now if campaign.enabled === 'active' i want to set v-model to on , or if
campaign.enabled === 'inactive' than off.

i tried to add logic to v-model in few ways like: v-model="campaign.enabled === 'active' ? on : off" or to use a method but none worked. Any idea what will consider as best practice to achieve that?

Categories: Software

Vuex Modules Structure

Tue, 2017-07-25 09:02

Tried to find this across tutorials and examples, but didn't find anything related. I know it is kind of up to the developer to structure it, but I was wondering how should be the best approach to the following:

I have a store, with modules like:

- root/ --- app-store.js --- modules/ ----- tasks.js ----- another-module.js

and so on.

I get the whole idea of modules, namespacing. But I'm not quite sure how to handle this situation (example):

1 - I access the list of Tasks. 2 - You click on a task in the list, it displays a view with all the details. 3 - You do some changes on this task (update, delete, etc)

What I'm doing right now:

  • one single file called 'tasks.js'

  • it loads all tasks with the information of each one nested already

  • when I click, I set a 'currentTaskId' variable. All actions references this variable when updating/deleting/etc

  • I'm loading the task list with the ID as the key, so I can easily reference it by tasks[id], instead of doing a search everytime.

My doubts:

  • Is this structure ok? Or should I create a module just to handle a single object?

  • Is using the ID as a Key for the array really a good practice?

  • Any other input. I know Vuex is quite flexible about the structure, but I find myself trying to come up with a nice structure, but I'm afraid of being overthinking something that should be simpler.

Categories: Software

Can’t access to custom canvas attribute in Vue

Tue, 2017-07-25 09:01

Has anyone used this component with Vue?

https://www.npmjs.com/package/aframe-draw-component.

I want to use Advanced Usage with “aframe-draw-component”. it works with raw html but not vue.js.

I get this error: App.vue?b405:124 Uncaught (in promise) TypeError: Cannot read property ‘canvas’ of undefined at NewComponent.init (eval at

It can’t find the custom dependency “draw”.

Can somebody help me ?

Thanks.

Categories: Software

Real Time Chat In Laravel [on hold]

Tue, 2017-07-25 09:01

I want to build chat system. Where users of website can have real time communication. I have searched for this in laravel. Most frequetly used solution is laravel pusher. But this is paid and free version is limited. Can anyone tell me how do i acheive this realtime chat without using pusher. I also looked for socket io but they also use pusher. can i use socket io or something else wihout pusher.

Categories: Software

Vuejs sidemenu transition not working with position: fixed

Tue, 2017-07-25 08:55

I have a sidebar component I would like to animate in and out with a transition. I am using transform translateX (see CSS below).

However, the menu does not animate in properly (although it animates out properly). It works fine when I get rid of the position: fixed css property on the component, however, that leaves it not looking like much of a sidemenu (it is not properly positioned on the screen). With position fixed, it works except that the background color and position of the sidemenu div (and elements within it) aren't finalized until after the animation is over.

So it looks gross. I've looked all over and found similar issues on here, but nothing that led me to a solution other than to use other peoples' pre-built components. (I would like to avoid doing that.)

Here is my html (from parent component) in webpack's vue-loader:-

<transition name="slide"> <app-menu v-if="menuToggled" :untoggle="toggleSidebar"> </app-menu> </transition>

Here is the sidemenu's CSS for the div:

.menu { position: fixed; top: 0; left: 0; bottom: 0; right: 0; display: flex; flex-direction: column; justify-content: space-between; background-color: black; padding: 10px; margin-right: 40px; text-align: center; }

Thanks! This is my first StackOverflow question. I hope I am not wasting anyone's time here. I very much appreciate constructive guidance of any form.

Categories: Software

How do I warn a user of unsaved changes before leaving a page in Vue

Tue, 2017-07-25 06:18

I have an UnsavedChangesModal as a component that needs to be launched when the user tries to leave the page when he has unsaved changes in the input fields (I have three input fields in the page).

components: { UnsavedChangesModal }, mounted() { window.onbeforeunload = ''; }, methods: { alertChanges() { } }
Categories: Software

Howler.js start playing song while it's loading

Tue, 2017-07-25 06:12

I'm using Howler.js

https://github.com/goldfire/howler.js

https://github.com/Blocklevel/vue-howler

I have it all working with preload and autoplay properties. But the problem is that some of the songs are a bit bigger in size. Is there any way to start playing the audio while it's loading. As soon as possible?

Categories: Software

vue init webpack alphalayui strange thing

Tue, 2017-07-25 05:55

My environment:
OS:win10
Vue:2.82
Yarn:0.27.5
Nodejs:8.2.1
Other:Git-bash When I first use vue init webpack alphalayui to build a vue project,I find a strange thing.

It can get my Email-ID,I fell so amazed,This Email-ID just use in a software which named Foxmail.But I have many Email-ID in this computer.

I want to know how can vue init get my Email-ID?

Can someone help me? Thanks in advance.
$ vue init webpack alphalayui ? Project name (alphalayui) y ? Project name y ? Project description (A Vue.js project) y ? Project description y ? Author (alphayan <yanyq@sdkej.com>) y ? Author y ? Vue build standalone ? Install vue-router? (Y/n) y ? Install vue-router? Yes ? Use ESLint to lint your code? (Y/n) y ? Use ESLint to lint your code? Yes ? Pick an ESLint preset (Use arrow keys) ? Pick an ESLint preset Standard ? Setup unit tests with Karma + Mocha? (Y/n) y ? Setup unit tests with Karma + Mocha? Yes ? Setup e2e tests with Nightwatch? (Y/n) y ? Setup e2e tests with Nightwatch? Yes

Categories: Software

In Vuejs, how to add watcher to all props and use the same function as a callback?

Tue, 2017-07-25 04:58

As the title, I want to add watcher and the same callback for all of the props, but I neet to code like this in sub-component:

<script> export default { props: { a: String, b: String, c: String }, watch: { a (v) { this.handler(v) }, b (v) { this.handler(v) }, c (v) { this.handler(v) }, }, methods: { handler (v) { // code... } } } </script>

And do you know how to simplify this?

Categories: Software

How to use PostCSS in Vue.js?

Tue, 2017-07-25 04:53

What's the recommended way to handle PostCSS in Vue.js (webpack template)?

I searched it in many places but still can't find a good solution.

Please, give an example using the most used plugins, like cssnext, precss and sugarss.

Categories: Software

How to warn unsaved changes when leaving a page in Vue?

Tue, 2017-07-25 04:25

I have several forms and input fields that I use in my Customize.vue file. I have to detect any unsaved changes and trigger a notification.

methods: { alertChange() { this.$notify.make('You have unsaved changes!', 'warning'); } }
Categories: Software

Vue Webpack Build Breaks Bulma CSS

Tue, 2017-07-25 03:07

I scaffold a webpack template for my vue project using the vue-cli. Subsequently, I added Bulma's CSS. When I run the program normally (npm run dev), the CSS renders properly. However, upon building the project for production (npm run build) with the default webpack configuration, the styling of the web app is now misaligned. Does anyone know how to resolve this issue?

For comparison:

Production Build of Vue with broken CSS

Dev version of Vue rendering CSS properly

The following is my webpack config (webpack.prod.conf.js)

var path = require('path') var utils = require('./utils') var webpack = require('webpack') var config = require('../config') var merge = require('webpack-merge') var baseWebpackConfig = require('./webpack.base.conf') var CopyWebpackPlugin = require('copy-webpack-plugin') var HtmlWebpackPlugin = require('html-webpack-plugin') var ExtractTextPlugin = require('extract-text-webpack-plugin') var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') var env = config.build.env var webpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true }) }, devtool: config.build.productionSourceMap ? '#source-map' : false, output: { path: config.build.assetsRoot, filename: utils.assetsPath('js/[name].[chunkhash].js'), chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') }, plugins: [ // http://vuejs.github.io/vue-loader/en/workflow/production.html new webpack.DefinePlugin({ 'process.env': env }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, sourceMap: true }), // extract css into its own file new ExtractTextPlugin({ filename: utils.assetsPath('css/[name].[contenthash].css') }), // Compress extracted CSS. We are using this plugin so that possible // duplicated CSS from different components can be deduped. new OptimizeCSSPlugin({ cssProcessorOptions: { safe: true } }), // generate dist index.html with correct asset hash for caching. // you can customize output by editing /index.html // see https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ filename: config.build.index, template: 'index.html', inject: true, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true // more options: // https://github.com/kangax/html-minifier#options-quick-reference }, // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency' }), // split vendor js into its own file new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function (module, count) { // any required modules inside node_modules are extracted to vendor return ( module.resource && /\.js$/.test(module.resource) && module.resource.indexOf( path.join(__dirname, '../node_modules') ) === 0 ) } }), // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', chunks: ['vendor'] }), // copy custom static assets new CopyWebpackPlugin([ { from: path.resolve(__dirname, '../static'), to: config.build.assetsSubDirectory, ignore: ['.*'] } ]) ] }) if (config.build.productionGzip) { var CompressionWebpackPlugin = require('compression-webpack-plugin') webpackConfig.plugins.push( new CompressionWebpackPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: new RegExp( '\\.(' + config.build.productionGzipExtensions.join('|') + ')$' ), threshold: 10240, minRatio: 0.8 }) ) } if (config.build.bundleAnalyzerReport) { var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin webpackConfig.plugins.push(new BundleAnalyzerPlugin()) } module.exports = webpackConfig

Categories: Software

Pages