Software
vue.js form submit did not get the new value of model-bind
I have a form
HTML:
<form ref="myForm" action="/AAA/BBB" method="get"> <input type="text" hidden="hidden" v-model="myValue" name="myName" /> </form> <button v-on:click="Send">Click me</button>JS
new Vue({ data: { myValue: 1 }, methods: { Send: function() { this.myValue = 2; this.$refs.myForm.submit(); } } })When i click the button, it will send the value: 1
I'm sure that the value was modified before form submit
Vue.js + Firebase - How to display deeply nested Database
this is my first question here because this is making me crazy. I am fiddling around with firebase and vue.js trying to loop thru my database(key-value) construct.
Below is my exported json:
{ "city" : { "new york" : { "zipcode" : { "10039" : { "street" : { " W 152nd St" : [ "263", "250", "21" ] } }, "02116" : { "street : { " W 155nd St" : [ "3", "25", "21" ] } } } }, "boston" : { "zipcode" : { "02116" : { "street : { "Berkeley St" : [ "161", "65", "13" ] } } } } } }What else should I tell you? I thought this structure would help me generating a quad-devided depented dropdown like [city [v]] [zipcode [v]] [street [v]] [number [v]].
Thanks in advance for your time and help.
Data-binding with <slot> in Vue.js
I created a login panel in Vue.js using Bootstrap CSS framework. Also, InputGroup component, because of help on back-end side. The purpose is not to write id="user_id" in Login.vue component, but in InputGroup.vue. It must be dynamic, in this case it does not write manually "user_id", but only takes data from the "field" props. The second problem is how to change the class, when is error on logging, add input class to tag "form-control-danger", but do not add class in "Login.vue" component, but in "InputGroup.vue" component. Thanks for help.
Login.vue
<form class="form-group has-error" @submit.prevent="checkUser"> <input-group field="user_id"> <label class="text-muted" for="user_id">User ID</label> <input class="form-control" type="number" id="user_id" v-model="form.userId" min="1" required> </input-group> <button class="btn btn-info btn-local">login</button> </form> <script> import InputGroup from './input-group/InputGroup.vue' import Form from './Form.js' // Form.js this is a class javascript file which helps in validation e.g. user ID. export default { name: 'LoginLocal', components: { 'input-group': InputGroup }, data() { return { form: new Form({ userId: '' }), }; }, methods: { checkUser() { this.form.post('/api/somewhere/users/' + this.form.userId + '/login') .then(() => this.$router.push('/')) .catch(error => window.handleError(error)) .catch(response => { if (response.status === 404) { return this.form.errors.recordCustom('user_id', 'Invalid User ID'); } }); }, }, }; </script>InputGroup.vue
<template> <div class="form-group" :class="{ 'has-danger': parent.form.errors.has(field) }"> <slot></slot> <div class="form-control-feedback">{{ $parent.form.errors.get(field) }}</div> </div> </template> <script> export default { props: ['field'], }; </script>nightwatch fails when initializing page object
I'm trying to test a Vue application. I have 2 simple page objects, and 2 simple spec files. When i run the e2e test, the first one (login) passes with no problem but the second one fails with this error:
Error: No selector property for element "client" Instead found properties: capabilities,globals,sessionId,options,launchUrl,launch_url,screenshotsPath,Keys,session,sessions,timeouts,timeoutsAsyncScript,timeoutsImplicitWait,elemen t,elementIdElement,elements,elementIdElements,elementActive,elementIdAttribute,elementIdClick,elementIdCssProperty,elementIdDisplayed,elementIdLocationInView,elementIdLocation,elementIdName,elementIdClear,elementIdSelected,elemen tIdEnabled,elementIdEquals,elementIdSize,elementIdText,elementIdValue,submit,source,contexts,currentContext,setContext,getOrientation,setOrientation,moveTo,doubleClick,mouseButtonClick,mouseButtonDown,mouseButtonUp,execute,execut eAsync,execute_async,frame,frameParent,window,windowHandle,windowMaximize,window_handle,windowHandles,window_handles,windowSize,windowPosition,refresh,back,forward,screenshot,url,status,title,keys,cookie,acceptAlert,accept_alert, dismissAlert,setAlertText,getAlertText,dismiss_alert,sessionLog,sessionLogTypes,click,clearValue,getAttribute,getCssProperty,getElementSize,getLocation,getLocationInView,getTagName,getText,getValue,isVisible,moveToElement,setValu e,submitForm,sendKeys,switchWindow,resizeWindow,setWindowPosition,maximizeWindow,saveScreenshot,getTitle,closeWindow,init,urlHash,getCookies,getCookie,setCookie,deleteCookie,deleteCookies,injectScript,getLogTypes,getLog,isLogAvai lable,waitForElementNotPresent,waitForElementNotVisible,waitForElementPresent,waitForElementVisible,end,pause,perform,useCss,useRecursion,useXpath,page,expect,assert,verify,currentTest,parent,name at new Element (C:\aquaprojects\src\bitbucket.org\scalock\tenantmanager\client\node_modules\nightwatch\lib\page-object\element.js:11:11) at C:\aquaprojects\src\bitbucket.org\scalock\tenantmanager\client\node_modules\nightwatch\lib\page-object\page-utils.js:39:35 at Array.forEach (native) at C:\aquaprojects\src\bitbucket.org\scalock\tenantmanager\client\node_modules\nightwatch\lib\page-object\page-utils.js:35:24 at Array.forEach (native) at module.exports.createElements (C:\aquaprojects\src\bitbucket.org\scalock\tenantmanager\client\node_modules\nightwatch\lib\page-object\page-utils.js:34:14) at Object.Page (C:\aquaprojects\src\bitbucket.org\scalock\tenantmanager\client\node_modules\nightwatch\lib\page-object\page.js:19:6) at Object.parent.(anonymous function) [as tenant] (C:\aquaprojects\src\bitbucket.org\scalock\tenantmanager\client\node_modules\nightwatch\lib\core\api.js:469:16) at Object.before (C:/aquaprojects/src/bitbucket.org/scalock/tenantmanager/client/test/e2e/specs/tenants.spec.js:7:26) at Object. (C:\aquaprojects\src\bitbucket.org\scalock\tenantmanager\client\node_modules\nightwatch\lib\util\utils.js:35:8)
login.js:
module.exports = { url: 'http://localhost:8080/#/login', elements: { app: '#app', loginSection: '.login-page', title: 'h3', submitButton: '.btn-primary', username: '#username', password: '#password' } }login.spec.js:
let login = null module.exports = { before: function (client) { console.log('*********** Init login page *******************') login = client.page.login() }, 'open login page': function () { login .navigate() .waitForElementVisible('@app', 5000) .assert.elementPresent('@loginSection') .assert.containsText('@title', 'Tenant Manager Login') }, 'try to login': function () { login.setValue('@username', 'administrator') login.setValue('@password', '1234') login.click('@submitButton') login.waitForElementNotPresent('@submitButton') }, after: function (client) { client.end() } }This one passes, the other one, which is basically copy/paste, with a few changes, fails on this line:
tenant = client.page.tenant()
tenant.js:
module.exports = { url: 'http://localhost:8080/#/tenants', elements: { tab: '#tenants', tenantsFilter: '.tenants-filter input', statusFilter: '.status-filter input', add: '.add-tenant' } }tenants.spec.js:
let tenant = null module.exports = { before: function (client) { console.log('*********** Init tenant page *******************') tenant = client.page.tenant() }, 'open tenant page': function () { console.log('*********** Navigating to tenant page *******************') tenant .navigate() .waitForElementVisible('@tab', 5000) .assert.elementPresent('@tenantsFilter') // .assert.containsText('@title', 'Tenant Manager Login') }, after: function (client) { client.end() } }IS there a way to edit External Vue.js plugins from inside the component file that imports it?
For example, I'm using vue-charts.js and imported it into my root component:
import VueChartjs from 'vue-chartjs'; Vue.component('bar-chart', { extends: VueChartjs.HorizontalBar, ... })Now VueChartjs is a wrapper for Charts.js so the component comes with its own template. I'd like to be able to edit that template within VueChartjs.HorizontalBar or the component bar-chartthat I mounted it onto.
Is there anyway to do this within this root component?
jQuery plugins not initialised in vuejs when loading a page using vue-router, Is it possible
I have a collection of jQuery plugins in the file jquery-plugin-collection.js and I initialise the plugins in the file custom.js. When I reload the page, all the plugins are being initialised. but when I load the page using vue-router, the plugins are not initialised. I made alot of google research with no result. Am wondering if am the first to face this issue.
v-show and v-if don't work on Laravel blade
This is not a duplicated question because I cannot find on SO a situation as simple as mine.
I'm manually trying to recreate an accordion
My html:
@foreach($device_menu_data['top_brands'] as $top_brand) <div class="brand_name" v-on:click="setVisibleBrand('{{$top_brand->brand}}')" > {{ $top_brand->brand }} <i class="fa fa-arrow-down device-list-toggler"></i></span> </div> <div class="brand_devices" v-if="visibleBrand === '{{$top_brand->brand}}'"> ....content of the duv </div> @endforeachMy js:
const open_device_menu_app = new Vue({ el: '#layout_header_container', data: { visibleBrand: 'none', }, methods: { setVisibleBrand: function(brand_name) { this.visibleBrand = brand_name; console.log(this.visibleBrand); } } });When I click on brand name, the console logs the right name. I was expecting that the specific brand_device will be shown after a click on the brand_name. But this doesn't happen. Both using v-if and v-show do not change.
Why?
How to make timeline in Vue.js?
Does anyone know good libraries for timelines? I tried vis.js, but couldn't figure out how to include it to my vue component. (btw, I'm using webpack)
Laravel Vue js2 and Ckeditor
I'm using vue js in my ckeditor to change content when clicking the language in my input select
The v-model of my select is "language", and the v-model of my ckeditor textarea is "templateContent"
<template> <div id="edit_template"> <div class="form-group"> <label class="col-md-2 control-label">Language :</label> <div class="col-md-4"> <select class="form-control" name="language" id="language" v-model="language"> <option v-for="language in languages" v-text="language" :value="language"></option> </select> </div> </div> <div class="clearfix"></div> <div class="form-group"> <label class="col-md-2 control-label">Content :</label> <div class="col-md-offset-2 col-md-10"> <div class="bootstrap-admin-panel-content"> <textarea id="ckeditor_full" name="cancellationContent" v-model="templateContent"> </textarea> </div> </div> </div> </div> </template>This is my vue-js code.
export default { props: ['emailTemplate'], name: 'edit_template', data () { return { languages: ['English','Dutch','French','German','Italian','Russian','Spanish','Swedish'], language: 'English', templateContent: '', }; }, mounted(){ this.templateContent = this.emailTemplate.english_content }, watch: { language(value) { this.$nextTick( () => { if(this.language =='English'){ this.templateContent = this.emailTemplate.english_content } else if(this.language =='Dutch'){ this.templateContent = this.emailTemplate.dutch_content } else if(this.language =='French'){ this.templateContent = this.emailTemplate.french_content } else if(this.language =='German'){ this.templateContent = this.emailTemplate.german_content } else if(this.language =='Italian'){ this.templateContent = this.emailTemplate.italian_content } else if(this.language =='Russian'){ this.templateContent = this.emailTemplate.russian_content } else if(this.language =='Spanish'){ this.templateContent = this.emailTemplate.spanish_content } else if(this.language =='Swedish'){ this.templateContent = this.emailTemplate.swedish_content } else{ this.templateContent = ''; } if(this.templateContent == null){ this.templateContent = ''; } }) } } }; </script>the model "templateContent" is changing value but the textarea of my ckeditor not change. I dont know if the ckeditor is compatible in vue.
Laravel, Vue refresh order after axios
I have problem with refreshing data afer done axios method. I have statuses to change. When someone change status I want to have only status name without buttons, but when I do this, order is not refreshing, It works only when I go somewere else and go back to this site, then actual order is load, button is gone and everything works. How to do, that when someone change styatus, then new order i load and button is gone at the same time?
Here is my code:
<div v-if="(order.order_products[key].statuses[0].id) == 4 && orderLastStatus != 3"> <div> <button v-on:click="changeProductStatus(order_product.id, status.id)" v-for="status in availableStatuses" v-bind:value="status.id" >{{status.name}} </button> </div> </div> <div v-else> {{order.order_products[key].statuses[0].name}} </div>And Vue:
changeProductStatus: function (orderProductId, statusId) { var self = this; if (confirm("Are you sure You want to change status?")) { axios.post("/order/" + orderProductId + "/changeStatus", {"status_id": statusId}) .then(function (response) { self.selected[orderProductId] = statusId; console.log(self.selected); }) } }how to pass multiple parameters in url when using vuejs
Hey i am trying to pass two parameters in my url for a simple spa and the params values will be extracted from the url using an api and passed to the server here is the url:
http://localhost:8080/#/game/username/token
but when i am hitting the url its passing this in the network:
Request URL:http://localhost:8080/api/game/usernametoken
and hence it is not hitting the right api
Vue client-side hydration
I am wondering where it possible to find out if vue client-side was hydrated or not?
Of cource, my server app has provided a valid html to the client corresponded this docs https://ssr.vuejs.org/en/hydration.html
Example:
<div id="app" data-server-rendered="true"> ... </div>
Somebody knows?
Thanks.
Vue JS2 parent and child checkboxes
I have a list of lists:
<ul> <li v-for="subregion in continents"> <input type="checkbox" :id="subregion[0].subregion" > <label :for="subregion[0].subregion">{{ subregion[0].subregion }}</label> <ul> <li v-for="country of subregion"> <input type="checkbox" :id="country.name" > <label :for="country.name">{{ country.name }} (+{{ country.callingCodes[0]}})</label> </li> </ul> </li> </ul> Full code here: https://jsfiddle.net/kw1vmvqy/
How do I implement a method so when I check/uncheck a continent check box it checks/unchecks all the country check boxes in it? Also if I uncheck one country check box - it unchecks the appropriate continent check box.
Prevent route change in Vue router
Some I am trying to create a link which will have a image in it. I am trying to make the inner div to do something without triggering the route change, how am I be able to achieve this? I have tried the event modified v-on:click.stop, but it doesn't seem to work, the route will still change after the .inner-div is clicked. Thanks in advance for your kind help.
Vuex getter not updating value after an array update
I'm trying to explore vuex, so what I'm trying to do is to get the count or an array when I remove or add values to it. Below are my codes.
home.vue template
<template> <div :class="page.class" :id="page.id"> <h3>{{ content }}</h3> <hr> <p>Registered users count {{ unRegisteredUserCount }}</p> <ul class="list-unstyled" v-if="getUnRegisteredUsers"> <li v-for="(unregistereduser, n) in getUnRegisteredUsers" @click="register(unregistereduser)"> {{ n + 1 }} - {{ unregistereduser.id }} {{ unregistereduser.fname }} {{ unregistereduser.lname }} </li> </ul> <hr> <p>Registered users count {{ registeredUserCount }}</p> <ul class="list-unstyled"> <li v-for="(registereduser, n) in getRegisteredUsers" @click="unregister(registereduser)"> {{ n + 1 }} - {{ registereduser.id }} {{ registereduser.fname }} {{ registereduser.lname }} </li> </ul> </div> </template> <script> export default { name: 'home', data () { return { page: { class: 'home', id: 'home' }, content: 'This is home page' } }, computed: { getUnRegisteredUsers() { if( this.$store.getters.getCountUnregisteredUsers ) { return this.$store.getters.getAllUnRegisteredUsers; } }, getRegisteredUsers() { if( this.$store.getters.getCountRegisteredUsers > 0) { return this.$store.getters.getAllRegisteredUsers; } }, unRegisteredUserCount() { return this.$store.getters.getCountUnregisteredUsers; }, registeredUserCount() { return this.$store.getters.getCountRegisteredUsers; } }, methods: { register(unregistereduser) { this.$store.commit({ type: 'registerUser', userId: unregistereduser.id }); }, unregister(registereduser) { this.$store.commit({ type: 'unRegisterUser', userId: registereduser.id }); } }, mounted: function() { } } </script>state.js
export default { unRegisteredUsers: [ { id: 1001, fname: 'John', lname: 'Doe', state: 'Los Angeles', registered: false }, { id: 2001, fname: 'Miggs', lname: 'Ollesen', state: 'Oklahoma', registered: false }, { id: 3001, fname: 'Zoe', lname: 'Mcaddo', state: 'New York', registered: false }, { id: 4001, fname: 'Jane', lname: 'Roberts', state: 'Philadelphia', registered: false }, { id: 5001, fname: 'Ellen', lname: 'Jennings', state: 'Houston', registered: false }, { id: 6001, fname: 'Joseph', lname: 'Reed', state: 'Boston', registered: false }, { id: 7001, fname: 'Jake', lname: 'Doe', state: 'Portland', registered: false } ], registeredUsers: [] }getters.js
export default { getAllUnRegisteredUsers(state) { return state.unRegisteredUsers; }, getAllRegisteredUsers(state) { return state.registeredUsers; }, getCountUnregisteredUsers(state) { return state.unRegisteredUsers.length; }, getCountRegisteredUsers(state) { return state.registeredUsers.length; }, getUserById(state) { } }mutations.js
export default { registerUser(state, payload) { //find user const user = _.find(state.unRegisteredUsers, { 'id': payload.userId }); // remove user from original array _.remove(state.unRegisteredUsers, { 'id': payload.userId }); // set user object key value user.registered = 'true'; // add user to new array state.registeredUsers.push(user); console.log(state.registeredUsers.length + ' - registered users count'); }, unRegisterUser(state, payload) { //find user const user = _.find(state.registeredUsers, { 'id': payload.userId }); // remove user from original array _.remove(state.registeredUsers, { 'id': payload.userId }); // set user object key value user.registered = 'false'; // add user to new array state.unRegisteredUsers.push(user); console.log(state.unRegisteredUsers.length + ' - unregistered users count'); } }During page load it renders the array count properly, but when I remove value to the registeredUsers and unRegisteredUsers the count is not updating. What am I missing here? Can anyone explain and what should I do to get the proper count? Thanks
Full Stack Setup with Python
In the years past, I've always used Angular 1.x for my front end which was as simple as including a single JS file at the time. Now with the rise of TypeScript in Angular, React, and others, there's now a need for a dedicated NPM build serves which compiles the source into vanilla JavaScript before serving the front-end as an independent project. Please correct me if my understanding of this is in anyway flawed.
At the moment I use Django for all of my backend applications, particularly a REST framework that will enable the frontend to function as a SPA. I've taken a liking to Vue.js as my frontend weapon of choice. My question is (and please forgive me if it seems a bit too broad) how do I setup my project and configure it properly so that I'm not running two servers for both the frontend and backend?
Again, back in the days of Angular 1.x and vanilla JavaScript all I had to do was include a minified angular.js in my static files folder in the backend and the same goes for the standalone version of Vue. Now I'm just so confused what is what and how to properly setting up a full stack project. If you guys, could weigh in, I'd very much appreciate it. Thank you in advance!
npm run dev # running the frontend for Vue.js manage.py runserver # and a Django DRF backendAssigning a parent element for each <slot> in Vue
I have a vue component, say my-component, which is like this:
<div class="outer"> <div class="inner"> <slot></slot> </div> </div>When I use the component:
<my-component> <p>This is paragraph 1 </p> <p>This is paragraph 2 </p> </my-component>The produced html becomes this (as it normally should):
<div class="outer"> <div class="inner"> <p>This is paragraph 1 </p> <p>This is paragraph 2 </p> </div> </div>But instead, I am looking for a way to produce something like this:
<div class="outer"> <div class="inner"> <p>This is paragraph 1 </p> </div> <div class="inner"> <p>This is paragraph 2 </p> </div> </div>How can I associate one inner div with each of the slot elements?
Responsive plot grid with measurements | javascript
I have to make a grid with ruler, that shows measurements between a few points on the grid (how many points and their coordinates on x,y will be given on page load)
So I have to make a functionality that allows to move any of the points to any of the four directions. Been searching for a library for that but did not find any. Something similar is here: http://jsdraw2d.jsfiction.com/demo/curvesbezier.htm
Does anyone of you know anything that would fit my needs? If not, would you recommend simple JS or VueJS to make custom grid for that? Thanks
Vue - Spotify API Auth. Login problems
I would like to create an app with Vue SPA (webpack) and the Spotify API. Unfortunately I can't get the Authentication right. So there is a basic code snippet from Spotify Which you can use to build your app. I tried to use that code and rewrite it so I can use it with Vue. That didn't work out quite nice and I have all kinds of problems. I've registered my App, and saved my details such as client id etc.
The original snippet from Spotify
http://jsfiddle.net/JMPerez/62wafrm7/
Problems
- Code doesn't log the response from the call. The pop up from spotify auth/login gives me a auth token in the url but doesn't close either. Also the display property stays false so it seems there is going something wrong at the login/auth function.
Code:
<button class="button is-spotify" :class="{display : display}" @click="getAuth()">Login to Spotify <i class="fa fa-spotify"></i></button>Methods
methods: { login(callback) { var CLIENT_ID = '3f6be5c8306741c8ab06713da0a92f59'; var REDIRECT_URI = 'http://localhost:8080/#/account'; function getLoginURL(scopes) { return 'https://accounts.spotify.com/authorize?client_id=' + CLIENT_ID + '&redirect_uri=' + encodeURIComponent(REDIRECT_URI) + '&scope=' + encodeURIComponent(scopes.join(' ')) + '&response_type=token'; } var url = getLoginURL([ 'user-read-email' ]); var width = 450, height = 730, left = (screen.width / 2) - (width / 2), top = (screen.height / 2) - (height / 2); window.addEventListener("message", function(event) { var hash = JSON.parse(event.data); if (hash.type == 'access_token') { callback(hash.access_token); } }, false); var w = window.open(url, 'Spotify', 'menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left); }, getUserData(accessToken) { axios({ method: 'get', url: 'https://api.spotify.com/v1/me', headers: { 'Authorization': 'Bearer ' + accessToken } }) }, getAuth() { this.login(function(accessToken) { this.getUserData(accessToken) .then(function(response) { console.log(response); this.display = true; }); }); } } // end of methodsSo when I copy the token from the url, and paste that in as a data property and run the getUserData seperately it does return me the data, like so:
<button class="button is-spotify" :class="{display : display}" @click="getUserData()">Login to Spotify <i class="fa fa-spotify"></i></button>getUserData function
getUserData() { axios({ method: 'get', url: 'https://api.spotify.com/v1/me', headers: { 'Authorization': 'Bearer ' + this.accessToken } }).then(function(response) { console.log(response); }) }But that's actually not what I want because than I have to set each hour a new token instead of users who just re authenticate each hour. So, I would like the same result as the basic snippet.
getAuth() { //run login + getUserData //maybe something like: get token and set it to this.accessToken }VueJS 2 debounce on multiple components
I have a Vue component that uses multiple sub-components on it. And on those sub-components I have a watcher that watches for data changes and processes those changes. I would like to implement debounce for this.
watch: { data: { handler: function () { this.processData() }, deep: true } }, methods: { processData: debounce(function () { console.log(this.id) }, 250),The problem is that debounce works so it executes only on the last sub-component.
I have found a solution for debounce function that accepts an additional id debounceWithId
However there problem is that if I specify this function as follows:
methods: { processData: debounceWithId(function () { console.log(this.id) }, 250, this.id),the last this.id is undefined.
What would be a correct way of using debounce in multiple components so the function fires separately on each component?