Vuejs

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

Vue, how to invoke to data from component

Fri, 2017-07-21 14:49

I'm trying to do, delete a row from my Vue data: todos, but my method is in component. And the second problem is thaht I can't fix, how to do if my input is checked or not? My method toggle return or is checked or not, but I cannot set this on my template. Here is code:

Vue.component('todoList', { props: ['todoObj'], template: '<tr>' + '<td>{{todoObj.description}}</td>' + '<input type="checkbox" v-on:click="toggle"/>' + '<button v-on:click="deleteTodo">delete</button>' + '</tr>', methods: { toggle: function () { axios.post('/todo/toggleTodo', { 'todoId': this.todoObj.id }).then(function (response) { Here will be code... I have to set to my checbox or is checked or not. This response return "yes" or "no" }); }, deleteTodo: function () { axios.post('/todo/deleteTodo', { 'todoId': this.todoObj.id }).then(function (response) { console.log(response); <- here i don't know how to delete my row from table from Vue data: todos }); } } });

And here is my rest code:

var app = new Vue({ el: '#appTest', data: { todos: [], todoText: '' }, methods: { addTodo: function () { var self = this; axios.post('/todo/addTodo', { 'newTodo': this.todoText }).then(function (response) { console.log(response); self.todos.unshift({ 'id': response.data.id, 'description': response.data.description, 'done': response.data.done } ); self.todoText = ''; }).catch(function (error) { var errors = error.response.data.description[0]; console.log(errors); self.error = errors; }); }, toggle: function () { console.log('toggle?'); } }, created: function () { var self = this; axios.get('/todo').then(function (response) { console.log(response.data); self.todos = response.data; } ); } });
Categories: Software

How to get cell value when that cell is clicked?

Fri, 2017-07-21 14:49

When user clicks a table cell Vue should be aware of its value. In this case I am trying to set an event and pass the value.

Is there any way I could write this better, maybe from Vue itself - for example when the cell is clicked first get its content? I have many cells in table, and this doesn't work, it works only if I remove PHP part and try to write it manually - @click="calculate_price(10)

<?php foreach ($tr as $td) : ?> <td @click="calculate_price(<?php echo $td['price']; ?>)"> <?php echo $td['price']; ?> </td> <?php endforeach; ?> var app = new Vue({ el: '#app', data: { price: 0 }, methods: { calculate_price: function (price) { console.log(price); } } })

Vue version is 2.4.2

Categories: Software

Vue JS - Calculator - read output string as value

Fri, 2017-07-21 14:40

I'm building a calculator to test out my Vue JS skills. I have the fundamentals working or at least set-up, however if I enter more than one number (i.e. 34) I can't get it to read 34 as a whole value, rather it adds 3 and 4 to the total. The snippet I'm having trouble with is here:

press: function(num) { if(this.currentNum == 0) { this.currentNum = num; this.output = num.toString(); } else { this.output += num.toString(); this.currentNum = this.output.parseInt(); } },

Here's the whole thing on CodePen for better context - https://codepen.io/ajm90UK/pen/BZgZvV

I think this is more of a JS issue rather than anything specific to Vue but even with parseInt() on the string I'm having no luck. Any suggestions on how I can read the display (output) would be greatly appreciated, been at this for hours now!

Thanks!

Categories: Software

vuejs Incorrect component definition

Fri, 2017-07-21 14:07

I have two components - 'HelloIndex' and 'HelloShow'.

The problem is that when I try to do this

this.$router.push({name: 'HelloShow', params: {id: 1}})

, then the 'HelloIndex' component is loaded instead of 'HelloShow'. In my router:

import Vue from 'vue' import Router from 'vue-router' import HelloIndex from '@/components/HelloIndex' import HelloShow from '@/components/HelloShow' Vue.use(Router) export default new Router({ routes: [ { path: '/index', name: 'HelloIndex', component: HelloIndex, children: [ { path: ':id/show', name: 'HelloShow', component: HelloShow } ] } ] })

HelloIndex.vue:

<template> <div class="hello"> <h1>{{ msg }}</h1> </div> </template> <script> export default { name: 'helloIndex', data () { return { msg: 'INDEX' } } } </script>

HelloShow.vue:

<template> <div class="hello"> <h1>{{ msg }}</h1> </div> </template> <script> export default { name: 'helloShow', data () { return { msg: 'SHOW' } } } </script>

App.vue

<template> <div id="app"> <button @click="show">show</button> <router-view></router-view> </div> </template> <script> export default { name: 'app', methods: { show () { this.$router.push({name: 'HelloShow', params: {id: 1}}) } } } </script>

main.js

import Vue from 'vue' import App from './App' import router from './router' new Vue({ el: '#app', router, template: '<App/>', components: { App } })

What's wrong with the names of the components?

Categories: Software

Check if prop passed validation

Fri, 2017-07-21 12:51

I have the following component property (it's basically for a bootstrap alert component):

props: { alertType: { validator: function (value) { return [ "success", "info", "warning", "danger" ].indexOf(value) >= 0; }, default: "danger" }, // Some more things computed: { classes: { //Compute the correct classes for the alert type var classesObj ={ 'alert-dismissible': this.dismissable }; classesObj["alert-"+this.alertType]=true; //Problem if invalid return classesObj; } }

This works well in the sense that if I don't provide an alert type it uses "danger", however if I do provide an alert type and it does not pass validation then the alertType is set to that value and a console warning is emitted (which as I understand is the intended behaviour).

My question is whether it's possible within the classes computed property to determine whether the alertType prop passed or failed validation (and ideally if it failed get and use the default value, based on the component prop definition.

Categories: Software

Removing query string parameter from Url

Fri, 2017-07-21 11:52

Coming from AngularJS I thought this would be easy enough in Vue.js 2 as well. But it seems this is difficult by design in Vue.

In AngularJS I can do this $location.search('my_param', null); which will effectively turn https://mydomain.io/#/?my_param=872136 into https://mydomain.io/#/.

In Vue I have tried this.$router.replace('my_param',null);, but it will only do https://mydomain.io/#/?my_param=872136 -> https://mydomain.io/#/my_param, leaving the empty my_param.

Isn´t there anyway in Vuejs2 to remove the query params from the Url? Should I resort to plain JS to achieve this?

Categories: Software

Vue project how to replace the existing dev-serve.js with the my express component

Fri, 2017-07-21 11:51

I am doing a login function vue project, login is in the express server to control, the generated dev-server.js can not meet the needs. How to write their own express code embedded in the existing project or how to rewrite dev-server.js. I tried to add the following code to test

app.get('*', function(req, res){ console.log('get /'); }); // serve pure static assets var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory); app.use(staticPath, express.static('./static')); var uri = 'http://localhost:' + port devMiddleware.waitUntilValid(function () { console.log('> Listening at ' + uri + '\n') });

Is the output of the "get /" But the page can not open, reported the following error

simple-line-icons.css Failed to load resource: net::ERR_EMPTY_RESPONSE style.css Failed to load resource: net::ERR_EMPTY_RESPONSE

It seems that the following code is not implemented, static path is not added. why? Is there any solution? Want to express the express code as a module independent of the existing project, how can I do?

Categories: Software

Laravel + Vue.js. Load more data when i click on the button

Fri, 2017-07-21 11:40

i have problem. When I click the button, it receives an entire database, but I want laod part database. How can I do this?

For example: After every click I would like to read 10 posts. Thx for help.

Messages.vue:

<div class="chat__messages" ref="messages"> <chat-message v-for="message in messages" :key="message.id" :message="message"></chat-message> <button class="btn btn-primary form-control loadmorebutton" @click="handleButton">Load more</button> </div> export default{ data(){ return { messages: [] } }, methods: { removeMessage(id){...}, handleButton: function () { axios.get('chat/messagesmore').then((response) => { this.messages = response.data; }); } }, mounted(){ axios.get('chat/messages').then((response) => { this.messages = response.data }); Bus.$on('messages.added', (message) => { this.messages.unshift(message); //more code }).$on('messages.removed', (message) => { this.removeMessage(message.id); }); } }

Controller:

public function index() { $messages = Message::with('user')->latest()->limit(20)->get(); return response()->json($messages, 200); } public function loadmore() { $messages = Message::with('user')->latest()->get(); // $messages = Message::with('user')->latest()->paginate(10)->getCollection(); return response()->json($messages, 200); }

paginate(10) Loads only 10 posts

Categories: Software

have a default choice for nested selects

Fri, 2017-07-21 11:23

I am building two nested select choices where the second depends on the first. I already builded them and they ae working. The problem is everytime i change the first one the second select box default value doesn't get show.

When i enter the first time it get updated because i set a intitial value for it.

here is my lopp code:

<div class="form-group"> <label class="control-label col-sm-3">Document Type</label> <div class="col-sm-9"> <select class="form-control" v-model="firstOption"> <option v-for="(item,index) in documentType"> {{ index }} </option> </select> </div> </div> <div class="form-group"> <label class="control-label col-sm-3">Document Selection</label> <div class="col-sm-9"> <select class="form-control" v-model="secondOption"> <option v-for="(item,index) in documentType[firstOption]">{{item.text}}</option> </select> </div> </div>

my data

i

mport data from '../interfaceData/documentType.json' import permissions from '../interfaceData/permissions.json' export default { name: 'app', data() { return { firstOption: "Business Development", secondOption: "Financial Proposal", documentType: data, } },

the documenttype that represent my nested lopps is loaded from a json, like the following:

{ "Business Development": [ { "text": "Financial Proposal", "key": 1 }, { "text": "Master Licence and Service Agreement", "key": 2 }, { "text": "Non-Disclosure Agreement", "key": 3 }, { "text": "Relatório de Missão", "key": 4 } ], "Configuration Management": [ { "text": "Configuration Management Plan", "key": 1 }, { "text": "Configuration Management Plan For Implementation Projects", "key": 2 } ], "Delivery": [ { "text": "Acceptance Protocol", "key": 1 }, { "text": "Acceptance Protocol For Implementation Projects", "key": 2 }, { "text": "Installation Manual", "key": 3 }, { "text": "Product Release Notes", "key": 4 }, { "text": "Product Update Release Notes", "key": 5 }, { "text": "Release Checklist", "key": 6 }, { "text": "Release Notes", "key": 7 }, { "text": "Release Strategy", "key": 8 }, { "text": "Release Manual", "key": 8 } ], "Financial": [ { "text": "Monthly Consultant Report", "key": 1 } ], "Generic": [ { "text": "General Document", "key": 1 }, { "text": "Meeting Minutes", "key": 2 }, { "text": "Memorandum", "key": 3 } ], "Human Resources": [ { "text": "Acordo de Confidencialidade CMF", "key": 1 }, { "text": "Acordo Sobre Isenção de Horário de Trabalho", "key": 2 }, { "text": "Contrato de Trabalho a Termo Certo", "key": 3 }, { "text": "Software Discharge of Responsability", "key": 4 }, { "text": "Termo de Responsabilidade de Software", "key": 5 } ], "Project Management": [ { "text": "CloseDown Meeting Minutes", "key": 1 }, { "text": "Kick Off Meeting Minutes", "key": 2 }, { "text": "Progress Meeting Minutes", "key": 3 } ], "Quality Management": [ { "text": "Incident Report", "key": 1 }, { "text": "Policy Definition", "key": 2 } ], "Specification Documents": [ { "text": "Software Architecture Specifications", "key": 1 }, { "text": "Software Detailed Design", "key": 2 }, { "text": "Software Requirements Specification", "key": 3 }, { "text": "System Requirements Specification", "key": 4 }, { "text": "Task Breakdown", "key": 5 }, { "text": "Tecnical Specification", "key": 6 }, { "text": "Tecnical Specification For Implementation Projects", "key": 7 }, { "text": "User Requirement Specifications", "key": 8 } ], "Testing": [ { "text": "Test Case Specification", "key": 1 }, { "text": "Test Plan", "key": 2 }, { "text": "Test Report", "key": 2 } ], "Training": [ { "text": "Attendance Sheet", "key": 1 } ] }

any help? thanks

Categories: Software

How to load signalr.js in webpack inside Vue2

Fri, 2017-07-21 11:13

In this way:How to use a jQuery plugin inside Vue But ,Error: '$' is not defined What do I need to do, to get signalr working using webpack? Thank you!

Categories: Software

What would be a good class name in the root of a vue component?

Fri, 2017-07-21 11:07

I usually need to write "layout related" styles (e.g. display: flex, margin: ..., padding:...) in the root tag of a vue component. So I need to do this by adding a class in the root of a vue component. I want to name all of these classes as wrapper given that all of them just serve a single purpose - defining the layout of this particular component. And I intended to use scoped css to avoid these classes from interferencing with each other.

The problem is I cannot really do this for components in parent-child relationship because A child component's root node will be affected by both the parent's scoped CSS and the child's scoped CSS. (vue-loader)

Question: How would you like to name classes in root tag of a vue compoennt that just defines the layout?

P.S. I thought about giving them the same name as component's name. But some of the component names can be quit long (more than 10 characters). And since they have the same purpose, it makes more sense to give them a uniform name.

Categories: Software

unable to access a php file with session through vue.js

Fri, 2017-07-21 11:02

I am facing problem with vue.js

I am using php api to login where where session is created and variables are stored

I am getting success on login api but when I call the next api to get contents which requires a session, it is throwing an error saying no valid session, even though i am calling login api and it is creating session.

/***** my data ****/ data() { return { user: { email: '', password: '', institutionCode: '', subscriberName: '', levels: '1', country: 'IN', // vendorid: 'wfnsu5LK', // vendorkey: 'OHmYPEgLTibhxZMO', }, vendorInfo: { vendorid: 'wfnsu5LK', vendorkey: 'OHmYPEgLTibhxZMO' }, levels: [], login: { email: 'praveen@gmail.com', password: 'praveen' } } }, /***** my methods ****/ methods: { signIn() { alert('inside login'); var loginData={}; loginData.email = this.login.email, loginData.password = this.login.password, this.$http.get('https://vpremieretest.mobiotics.com/subscriber/v1/login', { params: { 'vendorid':this.vendorInfo.vendorid, 'vendorkey':this.vendorInfo.vendorkey, 'email': loginData.email, 'password': loginData.password } }) .then(response => { console.log(response); var login = $.parseJSON(response.bodyText); if(login.email == loginData.email) { //alert('successful login') this.$http.get('https://vpremieretest.mobiotics.com/subscriber/v1/content/', { params: { 'vendorid':this.vendorInfo.vendorid, 'vendorkey':this.vendorInfo.vendorkey } },{withCredentials: true}, {emulateJSON: true}) .then(response => { console.log(response); }) } else { alert('invalid credentials'); } }, error => { console.log(error); }) } } }
Categories: Software

Variable Doesn't Change in Vue.js

Fri, 2017-07-21 10:10

I can't change the variable qty in my computed properties.

getQuantity(){ return (qtyId) => { var qty = 0; axios.get( window.location.origin + '/api/quantity/' + qtyId) .then(res => { console.log(res.data.qty) qty = res.data.qty }) .catch() console.log(qty) return qty } },

It is an asynchronous request using axios. the console.log(res.data.qty) works fine it output 4 but the console.log(qty) is 0. I think it's because of asynchronous request... How can I make it work... TY

Categories: Software

How to stop form from submitting on keyup - Vue.JS

Fri, 2017-07-21 10:06

When I hit enter, the page refreshes and nothing is executed in my callback. I've tried taking the input out of the form but then nothing happens.

<form class="left"> <input id="search" class="expanded-input" type="text" @keyup.enter="submitSearch" placeholder="Press enter to search by artist or title"> <i class="material-icons">search</i> </form>

JS:

submitSearch(e) { e.preventDefault(); console.log("success"); return false; }
Categories: Software

running unit test leads with Webpack +Karma + Typescript + Vue to SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'

Fri, 2017-07-21 09:58

I have been struggling to setup a unit test enviroment. I have altered the webpack-template to use typescript and follow class based approach. For unit test I am using Karma, Mocha, Chai, PhantomJs and istanbul-instrumenter-loader for code coverage.

Wrote a simple test expect(1).to.equal(2) one and results are shown, but a big error is really annoying me at the moment SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'

I believe the following are the relevant files where I am doing something that does not make sense, please have a glance and help me restore some sanitystrong text

/** build/webpack.test.conf.js **/ var webpackConfig = merge(baseConfig, { // use inline sourcemap for karma-sourcemap-loader module: { rules: [ { test: /\.ts$/, enforce: "pre", loader: 'istanbul-instrumenter-loader', include: path.resolve('src/'), options: { compilerOptions: { sourceMap: false, inlineSourceMap: true } } }, ...utils.styleLoaders() ] }, devtool: '#inline-source-map', plugins: [ new webpack.DefinePlugin({ 'process.env': require('../config/test.env') }) ] }) /** build/webpack.base.conf.js **/ module.exports = { entry: { app: './src/main.ts' }, output: { path: config.build.assetsRoot, filename: '[name].js', publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath }, resolve: { extensions: ['.js','.ts', '.vue', '.json'], alias: { 'vue$': 'vue/dist/vue.esm.js', '@': resolve('src') } }, module: { rules: [ { test: /\.(js|vue)$/, loader: 'eslint-loader', enforce: 'pre', exclude: '/node_modules', include: [resolve('src'), resolve('test')], options: { formatter: require('eslint-friendly-formatter') } }, { test: /\.js$/, loader: 'babel-loader', exclude: '/node_modules', include: [resolve('src'), resolve('test')] }, { test: /\.vue$/, loader: 'vue-loader', options: vueLoaderConfig }, { test: /\.(ts)$/, loader: 'ts-loader', options: { appendTsSuffixTo: [/\.vue$/] } } } /** tsconfig.json **/ { "compilerOptions": { "module": "es2015", "moduleResolution": "node", "types": [ "node", "mocha", "sinon-chai" ], "target": "es5", "allowJs": true, "rootDirs": ["src"], "noImplicitAny": false, "experimentalDecorators": true, "rootDir": ".", "sourceMap": true, "strictNullChecks": true, "allowSyntheticDefaultImports": true, "lib": [ "es5", "dom", "es2017", "es2015.promise", "es2017.object" ], "baseUrl": "./", "paths": { "@/*": [ "src/*" ] } }, "exclude": [ "node_modules", "src/vue-shim.d.ts" ] } /** test/unit/karma.conf.js **/ const webpackConfig = require('../../build/webpack.test.conf'); module.exports = function (config) { config.set({ browsers: ['PhantomJS'], frameworks: ['mocha', 'sinon-chai'], reporters: ['spec', 'coverage'], files: ['../../node_modules/babel-polyfill/dist/polyfill.js','./index.js'], preprocessors: { './index.js': ['webpack', 'sourcemap'] }, webpack: webpackConfig, webpackMiddleware: { noInfo: true, stats: 'errors-only' }, coverageReporter: { dir: './coverage', reporters: [ { type: 'lcov', subdir: '.' }, { type: 'text-summary' } ] } }) } /** test/unit/index.js **/ import Vue from 'vue' Vue.config.productionTip = false const testsContext = require.context('./specs', true, /\.spec$/) testsContext.keys().forEach(testsContext) const srcContext = require.context('../../src', true, /^\.\/(?!main(\.ts)?$)/) srcContext.keys().forEach(srcContext)
Categories: Software

Need help resolving “[WDS] Disconnected” using vueJS and vue-cli

Fri, 2017-07-21 09:41

I am new to VueJS and am working some simple code to understand how to handle components. I am using a simple-webpack bundler in vue-cli. Right now all I have is a simple template... (App.vue)

<template> <h1>Server Status: Critical!</h1> <template>

and this simple javascript file (main.js)

import Vue from 'vue' import App from './App.vue'

new Vue({ el: '#app', render: h => h(App) })

I can see whole thing rendered at localhost:8080, but the console log is throwing a chain of errors at me. This following object...

[WDS] Disconnected! 40:45:10 log webpack-internal:///40:45:10 close webpack-internal:///40:130:3 socket/sock.onclose webpack-internal:///94:15:4 EventTarget.prototype.dispatchEvent webpack-internal:///21:51:5 SockJS.prototype._close/< webpack-internal:///64:356:5

followed by

[HMR] Waiting for update signal from WDS... 41:49:2 //and [WDS] Hot Module Replacement enabled. 40:41:10

Any idea whats going on?

Categories: Software

API + SPA Deployment Best Practices

Fri, 2017-07-21 09:22

Developing a SPA in the frontend (with Vue.js) which consumes endpoints from a (Laravel) API in the backend introduces some challenges that need to be tackled:

1. How to sync deployment when introducing new backend/frontend code

If the code is separated in two VCS repositories (frontend/backend) it can be challenging to sync deployment of both frontend and backend making sure that both finish at the exact same time. Otherwise this can lead to unexpected behaviour (e.g. calling endpoints that are not yet deployed or have changed). Anyone came up with a great solution for this? What is your best practice to tackle this problem? What if versioning every little change is not an option?

2. How to make sure that the frontend code of the SPA is being refreshed after deployment?

So you managed to keep your deployments in sync (see problem 1.), but how do you make sure that the SPA code of every currently active end user is being refreshed? With webpack code splitting enabled, the application might break immediately for users that are currently using your app in between a deployment.

How do you make sure that your users are being served the latest JS without having them reload the entire application on every request? What are best practices (besides forcing the user to refresh the entire page via websockets)? Are there solutions that allow currently active users to keep using the application without being forced to refresh while they might just finished something that's ready to be saved?

I am very interested in your findings, learnings and solutions!

Categories: Software

What is mean of curly brackets wraps codes

Fri, 2017-07-21 09:01

When I checked source code of Vue.js I saw that, there are some codes between two curly brackets and there is no any defination before it (like function, ()=> or another thing). I paste it on console and it runs. But how can I use it, when I dont assing it as a variable?

What is this? Why we should use this way when we write code?

.... var formatComponentName = (null); { var hasConsole = typeof console !== 'undefined'; var classifyRE = /(?:^|[-_])(\w)/g; var classify = function (str) { return str .replace(classifyRE, function (c) { return c.toUpperCase(); }) .replace(/[-_]/g, ''); }; warn = function (msg, vm) { var trace = vm ? generateComponentTrace(vm) : ''; if (config.warnHandler) { config.warnHandler.call(null, msg, vm, trace); } else if (hasConsole && (!config.silent)) { console.error(("[Vue warn]: " + msg + trace)); } }; tip = function (msg, vm) { if (hasConsole && (!config.silent)) { console.warn("[Vue tip]: " + msg + ( vm ? generateComponentTrace(vm) : '' )); } }; } ...
Categories: Software

Vue-directive: update vs componentUpdated

Fri, 2017-07-21 08:42

The doc states update is called after the containing component has updated and that compontedUpdated is called after the containing component and its children have updated. But what are the actual use cases for choosing one over the other?

Categories: Software

How to Hide "Filter By Name" search box under filterByColumn in vuejs?

Fri, 2017-07-21 08:07

I'm following a tutorial, but I would like to hide or remove this search box. I've looked through the Internet and seems I haven't found a solution yet.

I want to get rid of these two search boxes

My Code is like this:

Vue.use(VueTables.client, { compileTemplates: true, filterByColumn: true, sortable: false, texts: { filter: "Search:" }, datepickerOptions: { showDropdowns: true }, --- });

Is there any filterByColumn option to hide these two boxes?

Full code is here :https://jsfiddle.net/e0uLphvk/

Thanks!

Categories: Software

Pages