Software
vue-wizard-form step validation on v-for
I am working with vue-form-wizard plugin by https://github.com/cristijora/vue-form-wizard but I am having trouble with v-for, when I set the attribute "prop" with the "option" It validates all the radio inputs but is not validating correctly.
I figured out that I need to set the prop attr like prop="test.option" where test is my array, but since it is a loop the array name is on the key but I am not able to do this with vue prop="key.option"
<div id="app"><div v-for="(gu, key, index) in formInline" data-row-span="6"> <el-form-item label="Approved by" prop="radio" :rules="rules.xx.radio2"> <el-radio-group v-model="gu.radio"> <el-radio :label="'3'">optionA</el-radio> <el-radio :label="'6'">optionB</el-radio> </el-radio-group> </el-form-item> </div> </el-form> </tab-content> <el-button type="primary" slot="prev">Back</el-button> <el-button type="primary" slot="next">Next</el-button> <el-button type="primary" slot="finish">Finish</el-button> </form-wizard>
Refresh VueJS component with a response received from backend, using Axios and Laravel
I have a VueJs dynamically generated table made up with an array, which comes from a Laravel backend. This works fine.
I would like to manipulate the array (delete, add, change values, etc.) in the VueJS, send it back to Laravel, have it processed and refresh the page with the new array.
Since I am still learning, for now all I am trying to achieve is this: send the same array back to Laravel, return it back and have the page refreshed with "new" array.
What I have:
vue.js:
Vue.component('word', { props: ['word-list'], template: '#word-template', methods: { increment: function () { axios.post('/update',this.wordList); } }, }); new Vue({ el: '#root' });HTML:
<div id="root"> <word :word-list="{{json_encode($commonWords) }}"></word> </div> <template id="word-template"> <table class="table"> <thead> <tr> <th>Key</th> <th>Value</th> <th></th> </tr> </thead> <tbody> <tr v-for="(value, key) in wordList" :wordList="wordList"> <td> @{{ key }} </td> <td> @{{ value }} </td> <td><button v-on:click="increment" class="button">Refresh</button></td> </tr> </tbody> </table> </template>Laravel:
public function update() { $commonWords = request()->toArray(); return view('words.show', compact('commonWords')); }What works: I am hitting the backend, it properly receives the array and sends it back. So the Laravel part works fine.
But how can I refresh the table with the new array?
VueJS 2 conditional rendering in value binding
I simply try to let VueJS 2 render a inline condition while I add a value to an dom element. I know, that it is possible to use v-if to let elements appear or disappear based on conditions, but how can I use a inline-condition?
I will give an example. The following html describe my idea and I know that this lines generates an error. Both <span> elements are controlled by conditions which lets them appear or not and this works fine.
Now, I try to bind a value to the href attribute depending on a condition (which are in the parentheses for example).
<div id="vuemain"> <span v-if="diced < 6">Looser</span> <span v-if="diced == 6">Winner</span> <a :href="'https://link-to-whatever.com/'+{diced==6 : 'winner', diced<6 : 'looser'} ">LINK</a> </div>So after rendering by VueJS the <a> tag should be like:
<a href="https://link-to-whatever.com/winner"> <!-- If diced == 6 -->OR
<a href="https://link-to-whatever.com/looser"> <!-- If diced < 6 -->Do you understand what my problem is and is that somehow possible?
Many thanks in advance
Allan
How to populate empty array with a method in Vue
I'm trying to populate an empty array with a declared array variable in a computed function. I tried this but with no luck:
data: { hashtags: [] }, computed: { filteredHashtags () { var defaultHashtags = [ '#hr', '#acc', '#sales' ]; var fHashtags = _.chain( messages ) .pluck( 'hashtags' ) .flatten() .map( function ( tag ) { return tag && tag.trim() ? '#' + tag : null; }) .filter( Boolean ) .value(); fHashtags = _.union( fHashtags, defaultHashtags ); return fHashtags = data.hashtags; } }Simple Vue component not rendering
I am trying to learn Vue.JS, and the component I have made is not rendering on the page. This is my component:
import Vue from 'vue' const card = new Vue({ el: '#card', data: { title: 'Dinosaurs', content: '<strong>Dinosaurs</strong> are a diverse group of animals from the clade <em>Dinosauria</em> that first appeared at the Triassic period.' } })This is my html:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue Practice</title> </head> <body> <div id="card"> <header>{{ title }}</header> <div v-html="content"></div> </div> <script src="bundle.js"></script> </body> </html>And this is package.json (I realize most of the dependencies belong in devDependencies):
{ "name": "vue-practice", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "bundle": "browserify -t babelify -t vueify -e main.js > bundle.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "babel-plugin-transform-es2015-modules-commonjs": "^6.26.0", "babelify": "^7.3.0", "browserify": "^14.4.0", "vue": "^2.4.2", "vueify": "^9.4.1" }, "devDependencies": {} }When I load index.html in the browser, all it renders is {{ title }} and I am receiving no errors. Any explanation as to why this is happening would be appreciated!
How to construct vuelidate validation for 2 dates
I have 2 dates in a component—validFrom and validUntil—and the validation is that validFrom is required, and validUntil is optional but if present must be after validFrom. I'm struggling to figure out how to set up Vuelidate validations to capture this. To complicate it further, some of these data elements might not be present, so I'm also using dynamic validations to only return data about the dates if the component has them. Here's a simplified version of the data and validations I've got so far:
data: () => ({ editedEventData: { name: '', signupData: { code: '', validFrom: null, validUntil: null } } }), validations: { editedEventData: { name: { required, minLength: minLength(1), maxLength: maxLength(20) } }, signupData: { code: { maxLength: maxLength(20) }, validFrom: { required }, validUntil: { isAfterFrom (value) { return date.getDateDiff(this.eventData.signupData.validFrom, value) < 0 } } } }That kind of works when validUntil changes, but it doesn't update the validation when validFrom changes. I put a console.log() into the isAfterFrom() function, and I can see it is recomputed when validUntil is changed, but appears not to be dependent on validFrom. I guess simply accessing this.eventData.signupData.validFrom in the validation isn't enough. I also tried calling $v.editedEventData.signupData.validUntil.$touch() when validFrom is changed, but still nothing.
Is there some way to recompute that validation when another field changes?
update Vuex store from main proccess electron
How I can update a vuex store by commiting things from main proccess? for example:
In main thread:
import store from ../store ipc.on('someevent', (event, args) => { // do stuff with args store.commit('update-things') })and in the renderer update components with these modifications.
Edit: Real code:
main.js
import store from '../store' const {ipcMain} = require('electron') const WebTorrent = require('webtorrent') const client = new WebTorrent() ipcMain.on('addMagnet', (event, arg) => { client.add(arg, function (torrent) { var files = [] torrent.files.forEach(function (file) { files.push({ title: file.name, torrent: torrent.infoHash, index: torrent.files.indexOf(file), duration: '--:--' }) }) store.commit('addSongs', files) })and store mutation is like:
addSongs (state, newSongs) { newSongs.forEach(function (song) { state.songs.push(song) }) }store is in diferent directory that main.js if it's helps.
Axios POST request error in headers in Vue2
I am new to javascript and Vue.js
I am making a POST API call in Vuejs using axios and my backend is in node.js. I am getting error in the authorisation. It works fine in postman
My POST API Call is as follows:
import Vue from 'vue' import router from '../router' import axios from 'axios' const API_URL = 'http://localhost:8000/api/' const LOGIN_URL = API_URL + 'login' export default { login(credentials, redirect) { console.log(LOGIN_URL) axios.post(LOGIN_URL,{ headers: { 'Authorization': 'Basic YWtzaGF5OmFrc2hheQ==', 'Content-Type': 'application/json', 'Accept': 'application/json' }, data: { 'email': credentials.email, 'password': credentials.password } }).then(response => { console.log(response.data) router.push(redirect) }).catch(e => { console.log(e); }) } }When I make the api request my javascript console shows
Failed to load resource: the server responded with a status of 500(Internal Server Error)and my server console shows error
TypeError: Cannot read property 'username' of undefinedhere username is username in basic authorization.
Unknown custom element using VUE
I'm new to Vue and am having some trouble with a few things. First, off I was following this tutorial: eventbus. If I put all the code (html, JS and CSS) in one html file, this works just as described in this tutorial.
However, I have been reading and I was following a VUE cli app structure. I used vue init webpack vueapp01 So, I have an index.html file in the vueapp01 root folder, in the src folder I have an app.vue and two vue files in the components folder; the-box.vue and the-button.vue; along with all the other files loaded by the vue template webpack.
Instead of having all the code in one html file (which works) I have the code separated out like this: index.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>vueapp01</title> <script src="https://unpkg.com/vue/dist/vue.js"></script> </head> <body> <div id="app"></div> <!-- built files will be auto injected --> </body> </html> App.vue:
<template> <div id="the-example" class="container"> <h1>Building an Event Bus with <a href="https://vuejs.org" target="_blank">Vue.js</a></h1> <div class="row"> <div class="col-xs-6"> <the-button what="Event #1"></the-button> <the-button what="Event #2"></the-button> <the-button what="Event #3"></the-button> </div> <div class="col-xs-6"> <the-box name="Receiver #1"></the-box> </div> </div> </div> </div> </template> <script> import the-button from './components/the-button' import the-box from './components/the-box' export default { name: 'app', components: { the-button,the-box } } </script> <-- <script> /****************************************** The Central Event Bus Instance *******************************************/ let EventBus = new Vue(); </script> the-box.vue:
/****************************************** Example Root Vue Instance *******************************************/ new Vue({el: "#the-example"}); /****************************************** A sample Vue.js component that emits an event *******************************************/ let TheButton = Vue.extend({ name: "the-button", props: ["what"], template: ` <button class="btn btn-md btn-success the-button" @click="makeItHappen()">Sender: {{what}}</button> `, methods: { makeItHappen: function(){ EventBus.$emit("somethingHappened", this.what) } } }); Vue.component("the-button", TheButton); the-button.vue:
/****************************************** A sample Vue.js component that received an event *******************************************/ let TheBox = Vue.extend({ name: "the-box", props: ["name"], template: ` <div class="well"> <div class="text-muted">{{name}}</div> <div>{{respondedText}}</div> </div> `, data: function(){ return { respondedText: null } }, created: function(){ EventBus.$on('somethingHappened', (what)=>{ this.respondedText = 'Event Received: ' + what; }) console.log("Responder") } }); Vue.component("the-box", TheBox);
Currently, I'm getting the errors, "unknown custom element the-box", "unknown custom element the-button". I've tried switching the script and template orders to have templates load first but I still have no luck.
Any help would be greatly appreciated. Also, I assume I'm doing this correctly by separating these components out to separate files but if that is incorrect I'd gladly take criticism on the way I'm learning to use Vue.
Vue/Vuefire: Ok, I can open a modal, save a image file to firebase, but can't get it to view without a refresh
Lots of pieces, got them all working except one!
I can open a modal window, do a firebase image upload (with the correct call back to make sure the upload worked), save the image to firebase storage (using vuefire). And close the modal.
The image DOES NOT show up until I do a manual refresh, then displays fine. Also if the image has been cached, it works OK. Just can't figure out why I can't view the new image without that manual refresh.
CODE
HTML to Display image: edit.vue
<div> <img :src="showPhoto()" id="showPhoto" name="showPhoto" /> </div>VUE code to populate html and open modal
showModal: function() { this.$modal.show('save') }, showPhoto: function () { const photoName = this.residentObj['photo'] console.log('photoName', photoName) if (photoName) { const gsReference = storage.refFromURL('gs://connect-the-dots-ef09c.appspot.com/images/' + this.$route.params.id + '/' + photoName).getDownloadURL().then(function(url) { var img = document.getElementById('showPhoto') img.src = url }) } }Save uploaded image close modal, go back the parent page. I can push a new route, but that has no effect even though the image has changed.
save.vue
methods: { onFileChange(e) { const file = e.target.files[0]; const storageRef = firebase.storage().ref('images/' + this.$route.params.id + '/' + file.name); residentsRef.child(this.$route.params.id).update({photo:file.name}); storageRef.put(file).then(function(result) { alert("OK, file uploaded!") // this has no effect, and probably dont want to refresh the entire page this the "img src" // this.$router.push({name: 'edit', params: { id: this.$route.params.id }}); }}); this.closeModal () });Summary: I can save an image to firebase using vue/vuefire, but can't view the new image unless I do a manual refresh. A cached image works fine.
Thanks for any tips.
How to resolve Cross-Origin Request Blocked in vue.js?
I'd like to send Google oauth2 authentication from vue.js on my development machine. Here is the function:
authenticate: function (provider) { axios.get( this.BASE_URL + "/web/login" , { token: this.token, }).then(function(data){ console.log(data); }); }But I get this error on Firefox instead:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://accounts.google.com/o/oauth2/auth?client_id=something.apps.googleusercontent.com&... (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
I use go gin as backend and have set it to use CORS.
router.Use(cors.Middleware(cors.Config{ Origins: "*", Methods: "GET, PUT, POST, DELETE", RequestHeaders: "Origin, Authorization, Content-Type", ExposedHeaders: "", MaxAge: 86400, Credentials: true, ValidateHeaders: false, }))So wondering who can I fix this error.
i get a blank pdf with axios in vue js
this is the action the get the pdf from the server
genratePdf({ commit }, data) { console.log(data) axios.post('http://localhost:1337/getpdf', data,{ responseType: 'application/pdf' }).then((response) => { console.log(response) let blob = new Blob([response.data],{type:'application/pdf'}) var link=document.createElement('a'); link.href=URL.createObjectURL(blob); link.download="Report_"+new Date()+".pdf"; link.click(); }, (err) => { console.log(err) }) }when i console log the response i get this result
but when i console the blob variable it doesn't contain the data
and the pdf i get is blank
how to trigger a function in vuejs after the page is loaded?
I am trying to trigger a function which hides or show the images on the basis of data i have written two function one which calls the api which is in created hook and second function which renders the image . The problem is how do i call that second function after the dom is loaded , right now when i am trying to call in the first function or created it is returning me error that css cannot be changed of null.
created:function(){ this.loadlike()
}, methods:{ loadlike:function(){ var self = this this.$http.get('/api/user_profile').then(function (res) { self.tasksdata = res.body self.badges = self.tasksdata.data2 console.log(self.badges) console.log(this.tasksdata) console.log(this.max) }) }, getHumanDate : function (date) { return moment(date, 'YYYY-MM-DD hh-mm-ss').locale("en-gb").format('LL'); }, render_badges:function(){ var self = this var counter = 0; self.badges.map(function(e){ counter ++; console.log(counter) if(counter <=self.max){ document.getElementById("i").style.display = "initial"; } else{ document.getElementById("i").style.display = "none"; } }) }VUE, React, Angular. Javascript multi-module applications using Webpack
I search the way to split VUE 2 application to modules using Webpack. I found this example of the project structure:
app/ moduleA/ components/ vuex/ index.js routes.js moduleB/ components/ vuex/ index.js routes.js vuex.js Main.vue router/ vuex/ components/ -> shared main.jsOne of the main requirements is possibility to build application with choosen modules using configurable profiles. Is there some best practices to implement this approach? May be someone using similar approach with the other javaScript frameworks like Angular or React? There is a similar question: bundling large Vue application using webpack
VueJs: Failed To Mount Component
not sure what the problem is here, I'm using Vue Router and instead of loading the component it throws me this vague Error:
Failed to mount component: template or render function not defined. found in ---> <Anonymous> <Root>Here is my Entry Point (app.js) (note I'm using multiple Entries in Combination with the CommonsChunksPlugin):
import Vue from 'vue' import '../../../assets/css/main.css' import App from './app.vue' new Vue(App).$mount('#app')The Html File (app.html)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> </head> <body> <div id="app"></div> </body> </html>(app.vue)
<template> <div> <router-view></router-view> </div> </template> <script> import { router, } from './bootstrap.js'; export default { router, }; </script>The Router:
import Vue from 'vue'; import VueRouter from 'vue-router'; var routes = [ { path: '/login', name: 'login.index', component: require('./index/index.vue'), }, { path: '/', redirect: '/login', }, ]; Vue.use(VueRouter); export const router = new VueRouter({ routes, }); Vue.router = router; export default { router, };And Finally the Component:
<template> <div> <h1>Test</h1> </div> </template> <script> export default {} </script>The Router works, I get redirected to /login as expected but the Component wont load. Any Help would be greatly appreciated
Thanks in Advance, Jan
Vue $on not running my function when event $emit is emited, even though I can see the event triggered in Vue console
I am trying to test if my $on function is working. I can clearly see that the the Vue console is receiving the event emit, but the pre defined call back function in $on is not being called.
Here is the code:
<template lang="html"> <div class="test"> <Filters></Filters> <div> <ul class="o-list c-stores"> <Result v-bind:total="filteredRestuarants.length" v-bind:open="isOpen" v-on:toggle="toggleRestaurantList"></Result> <li v-for="(restaurant, index) in filteredRestuarants" class="c-stores__location" :class="{'first': isFirst(index), 'last': isLast(index, restaurants)}"> <Location :index="index" :store="restaurant" :link="() => setCurrentRestaurant(restaurant)"></Location> </li> </ul> </div> </div> </template> <script> import eventHub from './../../event-hubs/storefinder' import Location from './Location' import Filters from './Filters' import Result from './Result' export default { props: ["restaurants", "isOpen", "currentSearch"], data() { return { attributes : [], } }, head: { title: function () { return { inner: this.$t('storefinder.overview') } }, meta: function functionName() { return [{ name: 'og:title', content: this.$t('storefinder.overview') + ' - ' + this.$t('storefinder.name'), id: "og-title" }, { name: 'description', content: this.$t('storefinder.description'), id: "meta-description" }, { name: 'og:description', content: this.$t('storefinder.description'), id: "og-description" }, ] } }, components: { Location, Filters, Result },Here its being added to the eventHub
computed: { startEvents(){ eventHub.$on('addFilterTheRestaurants', (attribute) => {console.log("test")}); eventHub.$on('removeFilterTheRestaurants', (attribute) => {console.log("test")}); }, filteredRestuarants(rest) { let restaur = rest || this.restaurants; return this.restaurants; } }, methods: { toggleRestaurantList() { eventHub.$emit('showRestaurantList'); }, setCurrentRestaurant(restaurant) { this.trackRestaurantSelect(restaurant.publicNameSlug); this.$router.push({ name: "store", params: { restaurant: restaurant.publicNameSlug } }); }, trackRestaurantSelect(restaurantName) { dataLayer.push({ 'event': 'GAEvent', 'eventCategory': 'restaurants', 'eventAction': 'clickResult', 'eventLabel': restaurantName, 'eventValue': undefined, 'searchTerm': this.currentSearch && this.currentSearch.toLowerCase(), 'amountSearchResults': 1 }); }, created() { // eventHub.$on('addFilterTheRestaurants', (attribute) => this.filteredRestuarants.value = this.restaurants.forEach(rest => {console.log(rest)})); // eventHub.$on('addFilterTheRestaurants', (attribute) => {console.log("test")}); // eventHub.$on('removeFilterTheRestaurants', (attribute) => {console.log("test")}); }, beforeDestroy () { bus.$off('addFilterTheRestaurants') bus.$off('removeFilterTheRestaurants') }, isLast: function (idx, list) { return idx === list.length - 1; }, isFirst: function (idx) { return idx === 0; }, } } </script>Cant find much information on this topic anywhere.
Laravel Spark, only showing the cancel subscription option after adding a subscription plan
After connecting the stripe payment system with my Laravel Spark installation I quickly setup some subscription options. Next, I subscribed to one of them using the test credit cards. Everything seems fine at the Stripe dashboard. However, if go the subscriptions page, I only see a big CANCEL SUBSCRIPTION button and not the selected subscription as well as the other subscriptions. I didn't touch the Spark components since I'm afraid to break something... so most of the stuff is pretty vanilla except for the configuration input. I checked with Chrome developer and these are the errors that seems to be linked:
app.js:42231 [Vue warn]: Error in render function: "TypeError: Cannot read property 'active' of undefined" found in ---> <SparkUpdateSubscription> <SparkSubscription> <SparkSettings> <Root> warn @ app.js:42231 app.js:42318 TypeError: Cannot read property 'active' of undefined at Proxy.render (eval at createFunction (app.js:51564), <anonymous>:2:24583) at VueComponent.Vue._render (app.js:45869) at VueComponent.updateComponent (app.js:44288) at Watcher.get (app.js:44629) at new Watcher (app.js:44618) at mountComponent (app.js:44292) at VueComponent.Vue$3.$mount (app.js:49600) at VueComponent.Vue$3.$mount (app.js:51803) at init (app.js:45245) at createComponent (app.js:46884)Anyone had this error or have an idea to fix it?
Thanks in advance
Enclosing a router-link tag in an image in vuejs
Can I wrap or enclose a router-link tag in an image tag?
When I click the image, I want it to route me to the desired page.
D3 - How to zoom a map on click of marker?
I'm using d3 to create a map and following is my requirement :
1. Plot markers on map
2. On click of marker, zoom into the map and update the map with new markers.
3. On click of the new markers show a tooltip.
Till now, I've managed to do the steps 1 and 3, but I don't understand how to achieve step 2.
var self = this; var path; self.world = d3.select('#map') .append('svg:svg') .attr('width', self.width) .attr('height', self.height); self.projection = d3.geoMercator() .center([0, 50]) .scale(150) .rotate([0, 0]); path = d3.geoPath().projection(self.projection); self.g = self.world.append('g'); // // Uses world json file plot a actual map // self.g.selectAll('path') .data(topojson.feature(worldMapJson, worldMapJson.objects.countries).features) .enter() .append('path') .attr('d', path) .on('click', function (d) { console.log(d); }); // Append Div for tooltip to SVG self.div = d3.select('#map') .append('div') .attr('class', 'tooltip') .style('opacity', 0); //Adds markers circles = self.g.selectAll('circle') .data(self.cities) .enter() .append('circle') .attr('cx', function (d) { return self.projection([d.lon, d.lat])[0]; }) .attr('cy', function (d) { return self.projection([d.lon, d.lat])[1]; }) .attr('r', 5) .attr('class', 'circle') .style('fill', 'red') .on('mouseover', function (d) { //Shows tooltip on mouse hover self.div.transition() .duration(200) .style('opacity', 0.9); self.div.text('Some text') .style('left', (d3.event.pageX - 50) + 'px') .style('top', (d3.event.pageY - 210) + 'px'); } );Vue.js: EventBus.$on received value is not propagating
I am fairly new to vue and trying to figure out the best way to structure my event bus. I have a main layout view (Main.vue) inside of which I have a router view that I am passing a child's emitted info to like so:
<template> <layout> <router-view :updatedlist="mainupdate" /> </layout> </template> export default { data () { return { mainupdate: [] } }, mounted () { EventBus.$on('listupdated', item => { this.mainupdate = item console.log(item) }) } }The structure looks like: Main.vue contains Hello.vue which calls axios data that it feeds to child components Barchart.vue, Piechart.vue, and Datatable.vue
The axios call in Hello.vue populates a data property called list. I then check if updatedlist (passed as router prop from Datatable.vue to Main.vue when something changes) is empty, and if so set it to the value of list
I know that the event is being emitted and received by Main.vue because the console.log(item) shows the data. But my child components are not getting updated, even though they are using updatedlist as their data source. (If I reload the page, they will be updated btw, but why aren't they reactive?)