Software
How can I reset/erase a vuex store data?
In my /src/store/ folder I have actions.js, index.js, mutations.js and state.js which contain the following info
actions.js
export default {}index.js
import Vue from 'vue' import Vuex from 'vuex' import state from './state' import actions from './actions' import mutations from './mutations' Vue.use(Vuex) export default new Vuex.Store({ state, actions, mutations })mutations.js
export default { TOGGLE_LOADING (state) { state.callingAPI = !state.callingAPI }, TOGGLE_SEARCHING (state) { state.searching = (state.searching === '') ? 'loading' : '' }, SET_USER (state, user) { state.user = user }, SET_TOKEN (state, token) { state.token = token } }and state.js
export default { callingAPI: false, searching: '', serverURI: 'http://10.110.1.136:8080', user: null, token: null, userInfo: { messages: [{1: 'test', 2: 'test'}], notifications: [], tasks: [] } }Now, when a user logs in, I keep the state in as
this.$store.commit('SET_USER', response.data)Now, when a user logs out, I run my components/logout.vue file in which it has the following code:
export default { data() {}, created() { localStorage.setItem('vuex', null); this.$store.commit('SET_USER', null); window.localStorage.clear(); window.sessionStorage.clear(); } }But for some reason, the data is somehow persisted.
Vue resource, using the same form for inserts and updates
I'm using Vue resource to connect to my backend api. I have a form component which I use for both creating a new resource item and modifying existing resource items. The form works fine, but when I want to save the form, it needs to use the proper http method for the api call. If I am creating a new item, it should use the POST method, and if I'm updating an existing item it should use the PUT method. Right now, my form save method looks something like this:
if(this.itemId > 0) { // Update existing item myresource.update({id: this.itemId}, this.item).then(response => { //... }, response => { //... }); } else { // Post new item myresource.save({}, this.item).then(response => { //... }, response => { //... }); }Basically, I have to use an if statement to check whether to use the update or save resource functions, then the success/fail promises both use the same code. Is there some way to combine the two methods above with something like this:
var method = this.itemId ? 'PUT' : 'POST'; myresource.request(method, {id: this.itemId}, this.item).then(response => { //... }, response => { //... });The above code obviously doesn't work, but is there a similar way to accomplish this without using an if statement and repeating my success/fail promises for each request type?
Multiple vue files on the same element and Vuex state(Vuex + Vue.js + Laravel)
I have registered a global component in app.js of Laravel called <unread>. In one of my blade files, I created a new Vue instance to handle a functionality that sits on the same #app element.
The problem is that though global component is rendered in this page but vuex state is different from other blade files. My question is if its possible to get around this problem without making a separate component? And if its even valid to follow this approach.
I was not able to find an explanation or solution on this. Please enlighten me. Heres my code.
In app.js,
Vue.component('unread', require('./components/core/Unread.vue')); import { store } from './store' window.onload = function () { const app = new Vue({ el: '#app', store }); }In blade file,
@section('scripts') <script type="text/javascript"> window.onload = function() { new Vue({ el: '#app', data: { //data here }, //rest of code }); }; </script>My Unread.vue file,
<template lang="html"> <a href="#"> <span class="badge" style="background-color:red">4</span> </a> </template> <script> export default { mounted() { console.log('mounted') this.get_unread() }, methods: { get_unread() { this.$http.get('/ajax/get-unread') .then((nots) => { nots.body.forEach( (not) => { this.$store.commit('add_not', not) }) }) } } } </script>Note: I get the mounted console, but this.get_unread() is not sent to update the vuex state
Uncaught (in promise) TypeError: Cannot read property 'commit' of undefined
How to get golbal data in main.js file in Vue JS?
following code is from my main.js file. Here I am parsing data from a url using Vue object and it returns some array of data. Now, In the main.js file I have a another GraphChart object and here I need some data from tableData.
How it would be possible? or any other tricks ? Now I am getting nothing.
var tableData = new Vue({ data: { items: '' }, methods: { graphData: function () { var self = this; var testdata= ''; $.get( 'http://localhost:3000/db', function( data ) { self.items = data; }); }, }, created: function() { this.graphData(); }, computed:{ }); new GraphChart('.graph', { stroke: { width: 24, gap: 14 }, animation: { duration: -1, delay: -1 }, // series: needs data from ITEMS object series:items._data.radialChart[1] } )
VueJS: Can't reach "data" from callback
This is the first time I'm using VueJs, so this might be a very basic thing, but in one of my callbacks I try to set a new value to a value, saved in the "data" component.
But whenever I try to run this method, Vue says my "this" is undefined, so I can't set this new value.
export default { name: 'app', data() { return { collection : {}, } }, mounted: function(){ var event = contract.statuschangedEvent(function(error, result) { if (!error){ this.collection[result.args.id].status = result.args.status } }); ...The "contract" object is a web3 object, and the syntax should be fine according to this documentation
The error I'm getting is "Uncaught TypeError: Cannot read property '[object Object]' of undefined"
Creating a webpack.config with two configurations but with the same plugins
I am working on a vue.js based project, where I will have a SPA for the admin dashboard and an another SPA on the public side. I want to handle the projects separately, but build them in the same time. (or it would be nice to have something like: run build --public OR --admin (to specify which one to build))
I created a config array, and with this setup it creates the output but for some reason it doesn't minifies. With a single configuration it did.
I tried to put the plugins to the configs separately like plugins: [ .. ] but no success.
webpack.config.js:
var path = require('path') var webpack = require('webpack')
module.exports = [ { entry: { public : './resources/js/public-spa/main.js', }, output: { path: path.resolve(__dirname, './public/public-spa/dist/'), filename: '[name].build.js', chunkFilename: "public.[name].chunk.js" }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { 'scss': 'vue-style-loader!css-loader!sass-loader', 'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax' } } }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } } ] }, resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js' } }, devServer: { historyApiFallback: true, noInfo: true }, performance: { hints: false }, devtool: '#eval-source-map' }, { entry: { public : './resources/js/admin-spa/main.js', }, output: { path: path.resolve(__dirname, './public/admin-spa/dist/'), filename: '[name].build.js', chunkFilename: "admin.[name].chunk.js" }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { 'scss': 'vue-style-loader!css-loader!sass-loader', 'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax' } } }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } } ] }, resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js' } }, devServer: { historyApiFallback: true, noInfo: true }, performance: { hints: false }, devtool: '#eval-source-map' } ]; if (process.env.NODE_ENV === 'production') { module.exports.devtool = '#source-map' // http://vue-loader.vuejs.org/en/workflow/production.html module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new webpack.optimize.UglifyJsPlugin({ sourceMap: false, compress: { warnings: false, }, output: { comments: false, }, }), new webpack.LoaderOptionsPlugin({ minimize: true }), new webpack.optimize.AggressiveMergingPlugin() ]) }Vue v-for on first item containing property X call a method
Let's say I have a component which repeats with a v-for loop like so:
<hotel v-for="(hotel, index) in hotels"></hotel>And my hotels array would look like so:
[ { name: false }, { name: false }, { name: true }, { name: true } ]How could I perform an action when my v-for loop encounters the property name set to true only on the very first time it encounters this truthy property?
I know I could probably cache a property somewhere and only run something once and not run again if it has been set but this does not feel efficient.
Vue: on div click, go to url defined in data
I have this kind of objects in an array:
{ name: 'name1', url: 'http://url-1.tld' }, { name: 'name2', url: 'http://url-2.tld' }On div click, I want to to a window.location.href to the url, but I can't seem to get the url from the data to my method.
<div v-for="person in persons" v-on:click="select($event)"></div> select: function(event) { window.location.href( ??? ) }Anybody have suggestions?
Mozilla Announces 15 New Fellows for Science, Advocacy, and Media
Today, Mozilla is announcing 15 new Fellows in the realms of science, advocacy, and media.
Fellows hail from Mexico, Bosnia & Herzegovina, Uganda, the United States, and beyond. They are multimedia artists and policy analysts, security researchers and ethical hackers.
Over the next several months, Fellows will put their diverse abilities to work making the Internet a healthier place. Among their many projects are initiatives to make biomedical research more open; uncover technical solutions to online harassment; teach privacy and security fundamentals to patrons at public libraries; and curtail mass surveillance within Latin American countries.
<Meet our Ford-Mozilla Open Web Fellows>
Ford-Mozilla Open Web Fellows are talented technologists who are passionate about privacy, security, and net neutrality. Fellows embed with international NGOs for 10 months to work on independent research and project development.
Past Open Web Fellows have helped build open-source whistle-blowing software, and analyzed discriminatory police practice data.
Our third cohort of Open Web Fellows was selected from more than 300 applications. Our 11 2017 Fellows and host organizations are:
Sarah Aoun | Hollaback!
Carlos Guerra | Derechos Digitales
Sarah Kiden | Research ICT Africa
Bram Abramson | Citizen Lab
Freddy Martinez | Freedom of the Press Foundation
Rishab Nithyanand | Data & Society
Rebecca Ricks | Human Rights Watch
Aleksandar Todorović | Bits of Freedom
Maya Wagoner | Brooklyn Public Library
Orlando Del Aguila | Majal
Nasma Ahmed | MPower Change
Learn more about our Open Web Fellows.
<Meet our Mozilla Fellows in Science>
Mozilla’s Open Science Fellows work at the intersection of research and openness. They foster the use of open data and open source software in the scientific community, and receive training and support from Mozilla to hone their skills around open source, participatory learning, and data sharing.
Past Open Science fellows have developed online curriculum to teach the command line and scripting languages to bioinformaticians. They’ve defined statistical programming best-practices for instructors and open science peers. And they’ve coordinated conferences on the principles of working open.
Our third cohort of Open Science Fellows — supported by the Siegel Family Endowment — was selected from a record pool of 1,090 applications. Our two 2017 fellows are:
Amel Ghouila
A computer scientist by background, Amel earned her PhD in Bioinformatics and is currently a bioinformatician at Institut Pasteur de Tunis. She works on the frame of the pan-African bioinformatics network H3ABionet, supporting researchers and their projects while developing bioinformatics capacity throughout Africa. Amel is passionate about knowledge transfer and working open to foster collaborations and innovation in the biomedical research field. She is also passionate about empowering and educating young girls — she launched the Technovation Challenge Tunisian chapter to help Tunisian girls learn how to address community challenges by designing mobile applications.
Follow Amel on Twitter and Github.
Chris Hartgerink
Chris is an applied statistics PhD-candidate at Tilburg University, as part of the Metaresearch group. He has contributed to open science projects such as the Reproducibility Project: Psychology. He develops open-source software for scientists. And he conducts research on detecting data fabrication in science. Chris is particularly interested in how the scholarly system can be adapted to become a sustainable, healthy environment with permissive use of content, instead of a perverse system that promotes unreliable science. He initiated Liberate Science to work towards such a system.
Follow Chris on Twitter and Github.
Learn more about our Open Science Fellows.
<Meet our Mozilla Fellows in Media>
This year’s Mozilla Fellows cohort will also be joined by media producers. These makers and activists have created public education and engagement work that explores topics related to privacy and security. Their work incites curiosity and inspires action, and over their fellowship year will work closely with the Mozilla fellows cohort to understand and explain the most urgent issues facing the open Internet. Through a partnership with the Open Society Foundation, these fellows join other makers who have benefited from Mozilla’s first grants to media makers. Our two 2017 fellows are:
Hang Do Thi Duc
Hang Do Thi Duc is a media maker whose artistic work is about the social web and the effect of data-driven technologies on identity, privacy, and society. As a German Fulbright and DAAD scholar, Hang received an MFA in Design and Technology at Parsons in New York City. She most recently created Data Selfie, a browser extension that aims to provide users with a personal perspective on data mining and predictive analytics through their Facebook consumption.
Joana Varon
Joana is Executive Directress and Creative Chaos Catalyst at Coding Rights, a women-run organization working to expose and redress the power imbalances built into technology and its application. Coding Rights focuses on imbalances that reinforce gender and North/South inequalities.
Meet more Mozilla fellows. The Mozilla Tech Policy Fellowship, launched in June 2017, brings together tech policy experts from around the world. Tech Policy Fellows participate in policy efforts to improve the health of the Internet. Find more details about the fellowship and individuals involved. Learn more about the Tech Policy Fellows.
The post Mozilla Announces 15 New Fellows for Science, Advocacy, and Media appeared first on The Mozilla Blog.
add our own function to when something is added to a Vuejs data element
I have a fairly simple Vuejs app and am just learning Vuejs. When I add or delete from a data property, I'd like some other function to happen. The code is like this:
data: { pricings: null, }, mounted(){ var somePrice = {"name":"service price", "price":"2.45"} this.pricings.push(somePrice); }, methods:{ callMe: function(){ alert("call me"); } }I'd like when I add or delete from pricings for some other method (callMe in this case) to be called. I am sure this is possible but am not having luck finding how to do it.
Add Vue Dashboard with Laravel project
please how can i migrate a dashboard that uses Vuejs in vue-cli like Vuestic inside my laravel project who uses also vuejs but with mix Thanks.
Update a Google Map on input change with Vue.js
I am trying to update a Google Map automatically after a user enters values in 3 input fields: state, city, address.
I think I have most of the code to make this work but I am using a custom Vue directive that inserts the initial map. This is necessary because there is a v-if on the form that conditionally displays these inputs.
My code is as follows:
<fieldset v-if="activeStep === 1"> <strong><%= f.label :city %></strong><br> <%= f.text_field :city, class: 'form-control', 'v-model': 'city', 'v-bind:readonly': '!byAddress', 'v-on:change': 'updateLocation' %> <strong><%= f.label :state %></strong><br> <%= f.text_field :state, class: 'form-control', 'v-model': 'state', 'v-bind:readonly': '!byAddress', 'v-on:change': 'updateLocation' %> <strong><%= f.label :address %></strong><br> <%= f.text_field :address, class: 'form-control', 'v-model': 'address', 'v-bind:readonly': '!byAddress', 'v-on:change': 'updateLocation' %> <strong>Map</strong><br> <div id="map-container" v-map="setDefaultLocation()"> <div id='location-map'></div> </div> </fieldset>the style:
#location-map { height: 250px; } #map-container { padding: 15px 0; }the Vue:
Vue.directive('map', { // When the bound element is inserted into the DOM: inserted: function (el, binding) { var map = new google.maps.Map(document.getElementById('location-map'), { zoom: 15, draggable: false, panControl: false, scrollwheel: false, streetViewControl: false, fullscreenControl: false, center: binding.value, disableDoubleClickZoom: true }); var marker = new google.maps.Marker({ map: map, position: binding.value }); } }) const progress = new Vue({ el: '#listing-multistep', data: { activeStep: 0, city: '', state: '', address: '', lat: undefined, lng: undefined }, methods: { setDefaultLocation: function() { return {lat: 37.7749, lng: 122.4194} }, updateLocation: function() { var geocoder = new google.maps.Geocoder({types: ["geocode"]}); geocoder.geocode({'address': this.address + ', ' + this.city + ', ' + this.state }, function(response, status) { if (status == 'OK'){ marker.setVisible(true); map.setCenter(response[0].geometry.location); marker.setPosition(response[0].geometry.location); this.lat = response[0].geometry.location.lat(); this.lng = response[0].geometry.location.lng(); } else { marker.setVisible(false) this.lat = null; this.lng = null; } }); } } })The problem is that the map and the marker variables are defined within the context of the Vue.directive but are not accessible from the Vue methods.
I think the code should work if I can somehow modify the map and marker objects stored in Vue.directive.
Can anyone think of a way in which I might make this work?
Thanks in advance!
Change CSS class property with Vue.js
I'm using Vue.js and I want to change a CSS class property. The HTML code which uses the class is the following:
<div class="fillTimerBar"></div>
And the CSS code:
.fillTimerBar { width: 100%; height: 8px; }
From there I want to change the width class property using a computed property from the Vue component.
Which would be correct way if any?
Vue d3 set attribute callback can't access Vue data property
I have one component in Vue, and I want to draw two rectangles using d3. I try to set the x and y attribute of the rect element using a callback method defined in the Vue component.
But I can not access the data property set for Vue component inside this callback. Here is my component, I am getting confused further because when I hit the debugger and does console.log(this.svgHeight) in the Chrome DevTools console directly, it does log the svgHeight defined in the data.
<template> <v-container class="travel-pattern"> <v-layout> <v-flex xs12 id='svg-container'> </v-flex> </v-layout> </v-container> </template> <script> /* eslint-disable no-undef */ /* eslint-disable no-unused-vars */ export default { name: 'travel-pattern', data () { return { msg: 'Travel Pattern component', dataset: [{h: 50, w: 100}, {h: 80, w: 200}], svgHeight: 100, svgWidth: 500 } }, methods: { getRectHeight: d => { return d.h }, getRectWidth: d => { return d.w }, getRectX: (d, i) => { return (i * d.w) + 25 }, getRectY: d => { // return 50 debugger let x = this.svgHeight // here x gets undefined. return (x) }, getClickEvent: d => { debugger } }, mounted () { // 1. Draw two rectangles // 2. Each rectangle can be clicked // 3. Once clicked a pop up will appear with a text field // 4. Entering a color in the text field will change the other rectangles color // Create an SVG element var svg = d3.select('#svg-container') .append('svg') .attr('height', this.svgHeight) .attr('width', this.svgWidth) // Create a rectangle for each dataset var rectangles = svg.selectAll('rect') .data(this.dataset) .enter() .append('rect') // Actually draw the rectangles rectangles.attr('x', this.getRectX) .attr('y', this.getRectY) .attr('width', this.getRectWidth) .attr('height', this.getRectHeight) rectangles.on('click', this.getClickEvent) } } </script>HTML Tag in Array Value
The Requirement is to append an HTML element from Array Value to DOM
template: { 0: { h1: '<h1>Hi</h1>' }, 1: { h2: '<h2>Hi</h2>' }, 2: { h3: '<h3>Hi</h3>' } }I have a VueJS For Loop:
<div v-for="temp in template"> {{ temp.h1}} </div>DOM :
<h1>hi</h1>Ruby on Rails 5.1 & Vue.js 2.4.x – Testing with Karma, Jasmine – How to install?
I have Rails 5.1.x and Vue.js 2.4.x; I do not mix Rails and Vue.js in the frontend – only Vue.js is used
I added the following packages:
package.json
... "devDependencies": { "jasmine": "^2.8.0", "karma": "^1.7.1", "karma-chrome-launcher": "^2.2.0", "karma-jasmine": "^1.1.0", "webpack-dev-server": "^2.6.1" }, ...Q1: Where do I do the configuration? In webpack/test.js or some karma.conf.js file
Q2: What is in this conf file?
Q3: Do I need to install karma-webpack?
Vue2.4+ compile component behavior
So I've recently started working with Vue js. I'm attempting to dynamically add and remove Vue nodes. It's a bit difficult to describe the issue so I've created a demo to illustrate it.
Vue.component('context', { data() { return { test: '<context></context>', //Dummy recursive data to illustrate issue child: '' } }, methods: { addChild() { this.child = this.test }, removeChild() { this.child = '' } }, computed: { dynamic() { return Vue.compile(this.child) }, style() { return { 'background-color': '#' + randHex(6) } } }, template: ` <div :style="style" @click="addChild" @click.shift="removeChild"> <component :is="dynamic"></component> </div> ` }) new Vue({ el: '#app' }) function randHex(digits) { let hex = Math.floor(Math.random() * Math.pow(16, digits)).toString(16) return '0'.repeat(digits - hex.length) + hex } html, body { height: 100%; overflow: hidden; } div { width: 90%; height: 90%; } <script src="https://unpkg.com/vue@2.4.3/dist/vue.js"></script> <p>Click on the block to add, Shift-Click ro remove. Why does shift clicking always remove all inner blocks and not just the ones as children to the shift clicked block?</p> <div id="app"> <context></context> </div>
Above you will see that Clicking on the colored rectangles adds a inner child as intended. However when you shift click on a rectangle it not only removes its children, but ALL children! (Even ones that are parents to the current node.)
Initially I had thought the click event was "bleeding through" to the lower elements, I did however create a bit more complex test that offset the elements position to not be above one another, this still produced the same strange behavior.
Any help on understanding / resolving this issue would be greatly appreciated.
How to use .vue files with Rails 5.1
I currently have one application.js file in which I've put all my Vue.js code, as follows:
import Vue from 'vue/dist/vue.esm'; document.addEventListener('DOMContentLoaded', () => { if(document.getElementById('dashboard-topbar')) { const dashboard = new Vue({ ... do stuff }) } if(document.getElementById('map')) { const map = new Vue({ ... do stuff }) } if(document.getElementById('something-else')) { const something-else = new Vue({ ... do stuff }) } }but I would like to separate these into their own .vue files. What's the recommended way of doing this?
Thanks!
Turbolinks causes vue js to load twice on every navigation
When opening page A - then B and then going back to Page A I will see
You are running Vue in dev mode
beeing logged twice. This also causes my components to flash.
I've added
<meta name="turbolinks-cache-control" content="no-cache">
To all my pages and already use Turbolinks adapter
import TurbolinksAdapter from 'vue-turbolinks' window.Vue.use(TurbolinksAdapter);Any Ideas on this?
How to tell when to create a new component?
I've been looking around behind the logic of when someone shall create a new component in a web application on angularjs / angular but I suppose this is more general and might apply on all component based front end frameworks.
I know that there are some principles like it should be abstract and reusable but is there any solid question which I might ask before creating a new component ?