Software
Vue sharing state between sibling components
I probably do not want to use vuex for state management yet as it is probably overkill for now. I took a look at https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication. I am using single file component so I am not sure where do I define the shared bus such that both components will have reference to it.
var bus = new Vue()ChildA.Vue
watch: { sideNav: (newValue) => { bus.$emit('sideNav-changed', newValue) } }ChildB.Vue
created () { bus.$on('sideNav-changed', data => { console.log(`received new value: ${data}`) // update own copy here }) }Parent.Vue
<template> <childA> </childA> <childB> </childB> </template>I want to watch any changes of sideNav on ChildA and emit it to ChildB to update its own value.
Why won't VueJS invoke methods from the created() function?
Learning VueJS and trying to do a simple API call on component load to put a list of repos onto my page. When I call and set the this.repos from the created() method, no problem. But if I set it as a method and then call it from this.getRepos nothing happens. No error, nothing. What am I missing about VueJS?
This works:
data: () => ({ msg: 'Github Repos', ok: 'Im practically giving away these repos', repos: [], }), methods: { }, async created() { const repos = await axios.get('https://api.github.com/orgs/octokit/repos'); this.repos = repos.data.map(repo => `<div class="box"><a href="${repo.html_url}"> ${repo.name} </div>`, ); },This DOES NOT work:
data: () => ({ msg: 'Github Repos', ok: 'Im practically giving away these repos', repos: [], }), methods: { getRepos: async () => { const repos = await axios.get('https://api.github.com/orgs/octokit/repos'); this.repos = repos.data.map(repo => `<div class="box"><a href="${repo.html_url}"> ${repo.name} </div>`, ); }, }, created() { this.getRepos(); },Any ideas? Thanks!
Lint SCSS in VueJS single file component with Webpack
I'm trying to lint the SCSS styling in the <style> tag of VueJS single-file componens using Webpack. I'm attempting to call the webpack loader scsslint-loader as preLoader within the vue-loader task of my Webpack build.
The single-file vue.js component....
<template lang="pug"> ... </template> <script> ... </script> <style lang='scss'> @import '/scss/core/colors'; .email { color: $primary_color; width: 320px; } </style>In Webpack(2.5) the vue-loader config looks like...
module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { preLoaders: { 'scss': 'scsslint-loader', 'sass': 'scsslint-loader' }, loaders: { 'scss': 'vue-style-loader!css-loader!sass-loader', 'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax' }, } } ] },The result from running Webpack...
undefined:1 No such file or directory @ rb_sysopen - ; ^ SyntaxError: Unexpected token N in JSON at position 0 at JSON.parse (<anonymous>) at linterResults (C:\wamp\www\spreadless\node_modules\scsslint-loader\dist\scsslint-loader.js:20:28) at C:\wamp\www\spreadless\node_modules\scsslint-loader\dist\scsslint-loader.js:57:13 at ChildProcess.exithandler (child_process.js:277:5) at emitTwo (events.js:125:13) at ChildProcess.emit (events.js:213:7) at maybeClose (internal/child_process.js:897:16) at Socket.stream.socket.on (internal/child_process.js:340:11) at emitOne (events.js:115:13) at Socket.emit (events.js:210:7) at Pipe._handle.close [as _onclose] (net.js:549:12)Questions are...
- Am I calling the scsslint-loader correctly as a vue-loader{preLoader} within the Webpack config?
- If so any idea on what is causing the no file error
vuejs include javascript library in spa
i'am creating spa application using vuejs and i find out that i have 3 option in loading my javascript library like bootstrap.js or jquery.js and other javascript library:
1. first is by include all javascript library that i will use in my application in index.html where my vuejs application will live but i find that there is some javascript library that not working to well
ex: there is some javascript library that calculate page height by selecting some div with specific id="page-container", but that div not loaded when page is rendered from server, so at that moment the javascript will throw error since id="page-container" not exist yet.
2. second is by adding it like this to all my javascript library js
// before you use your files in some components,you should package them // your local files export default { //export your file your_function(){ // defined your function ... } } // now your can use it // your component file <script> import local_file from 'your_file_relative_path' //now you can use it in the hook function created(){ //or other hook function local_file.your_function() //call your function } </script>but that mean i need to change every javascript library that i use...
3. third is by adding it using npm, and just in the vue component import it, it works okay and feels more natural but not all my javascript library are in npm, some of them is admin template related that i bought from themeforest and will never be in npm.
so which one is a better way or maybe there is much more better way that those 3 option that i find out? its hard to find any tutorial or discussion that mention adding other javascript library to spa vuejs most of them just put a bootstrap into index.html and done.
Vue js component does not work when VeeValidate is declared
My problem is that I use a Vue js plugin to generate forms dynamically: https://github.com/icebob/vue-form-generator, and when I use VeeValidate the plugin stops working with no errors. However, the moment I remove Vue.use(VeeValidate) , it works fine. So what could be causing the problem? Here is my code:
import VeeValidate from 'vee-validate'; import VueFormGenerator from "vue-form-generator"; Vue.use(VeeValidate, { errorBagName: 'vErrors' }); Vue.use(VueFormGenerator); new Vue({ el: '#action-button-settings', data: { model: { id: 1, name: "John Doe", }, schema: { fields: [{ type: "input", inputType: "text", label: "ID (disabled text field)", model: "id", readonly: true, disabled: true },{ type: "input", inputType: "text", label: "Name", model: "name", placeholder: "Your name", featured: true, required: true }] }, formOptions: { validateAfterLoad: true, validateAfterChanged: true }, }, methods:{ init() { console.log('hi'); }, } });HTML:
<template> <vue-form-generator :schema="schema" :model="model" :options="formOptions"></vue-form-generator> </template>Also, as you can see I rewrote VeeValidator computed property errors to vErrors because it was causing a conflict between the two libraries. Please help.
Send email after purchase without CMS
I'm creating a website using Bootstrap and VueJS. I need to implement a payment platform where an email is sent to the customer when he buys a product. Which is the best method to do that ? I saw that mailchimp is a good alternative, but I'm not using a CMS. Any idea ?
How do i bind select box with input in vuejs?
I try to bind select box with input so like this I have a select box with some option when selected that information will go to input and when some one put information in the input it should bind in select.Can't figure it out.
<div class="col-md-2 text-center"> <select class="form-control" v-model="selected"> <option v-for="item in inventory" :value="item" :key="item.id"> @{{ item.name }} </option> </select> <p> @{{ selected.id}} </p> </div> <input v-model="inputBind" placeholder="," type="text" class="form-control">and
new Vue({ el:'#app', data:{ inputBind:'', inventory: [ {name: 'MacBook Air', id: 1}, {name: 'MacBook Pro', id: 2}, {name: 'Lenovo W530', id: 3}, {name: 'Acer Aspire One', id: 4} ], selected: 2 }, created: function() { this.selected = this.inventory.find(i => i.id === this.selected); },Is the way I'm writing my Vue components correct?
Here's the way I am currently writing my Vue components. E.g.
<template> <NavBar></NavBar> <div class="Footer"> <div class="left"> <p>I'm a cool footer on the Left!</p> </div> <div class="middle"> </div> <div class="right"> <p>I'm a cool footer on the Right!</p> </div> </div> </template> <script> import NavBar from './NavBar.vue'; export default { name: 'Footer', components: { NavBar } data () { return { } }, methods: { } }My question is should I be writing my components like this instead? And if so, what is the difference?
Vue.component('my-component', { template: '<div>A custom component!</div>' }) new Vue({ el: '#example' })Delete a record from Ag-grid using rendered button in Vue file
I'm using an ag-grid to populate list records(rows) in a table. I'm trying to delete a record from the grid-table when the user clicks a "Delete" button in one of the cell. I'm able to add the "Delete" button to the grid but how can I capture the index of the clicked "Delete" in the table and remove that row.
table's grid options are defined in file specials.Vue
*function setGridOptions() { this.gridOptions = { columnDefs: [{ headerName: 'Model', field: 'scModel', editable: params => this.isCellEditable(params), newValueHandler: this.NewValueHandler, width: 120, }, { headerName: 'Delete ', width:50, field: 'delete', cellRenderer: deleteRecordCellRender, }, ], rowData: this.getInitialRowData(), headerHeight: 36, rowHeight: 28, suppressMovableColumns: true, suppressMenuMainPanel: true, suppressMenuFilterPanel: true, suppressMenuColumnPanel: true, suppressContextMenu: true, singleClickEdit: true, rowSelection: 'single', }; }*The 'Delete' column rendered from 'deleteRecordCellRender' defined in javascript file ag-gridFunction.js
*export function deleteSpecialRecordCellRender() {} deleteSpecialRecordCellRender.prototype.init = deleteSpecialRecordCellRenderInit; deleteSpecialRecordCellRender.prototype.getGui = deleteSpecialRecordCellRenderGetGui; function deleteSpecialRecordCellRenderGetGui() { return this.eGui; } function deleteSpecialRecordCellRenderInit() { console.log('deleteSpecialRecordCellRenderInit this: ', this); this.eGui = `<button class="btn btn-default btn-sm delete-row-button" rel="">Delete</a>`; }*delete-row-button function defined in specials.Vue file is
$('.delete-row-button').on('click', () => { console.log('made it'); console.log('scope: ', this); console.log('clicked row',$scope.gridOptions.api.getSelectedRows()) });But It's not getting the selectedRow due to a scope issue. How do I get the selected row index and delete after ?
Vuejs Component Route Dynamic Selection
I've got a Vue instance:
new Vue({ el: '#Application', router: Router, components: { 'ExampleDepartment', Application }, data: function() { return { } } });Inside of my application file, I import the template, sidebar action. Inside the template, I have the following:
<v-list-tile v-for="action in actions" :key="action.label" v-if="action.visibility == true"> ... </v-list-tile>Then inside, I have the following:
export default { watch: { $route: function() { this.getOrSetPageVisibility(); } }, methods: { getOrSetPageVisibility() { for(let index = 0; index < this.actions.length; index++) { if(this.actions[index].page == this.$router.currentRoute.name) { this.actions.$set(index, { visibility }, true); } } } }, data: function() { return { actions: [ { label: 'Add Sample', icon: 'add_circle', page: 'Sample', visibility: false } ] } } }So the issue, is every time the page switches I want to load a variation of menu items to the sidebar, but it won't let me modify the array. It complains that $set isn't valid or undefined, and it won't update the component on the change.
I can see that on the menu changes it executes my method through the watch, but fails when modifying the array.
How can I dynamically add to the menu based on selected page?
How to handle bootstrap tooltip in vueJS?
everyone)
I build a Russian-Chinese language economical game.
I want to do a tooltip over the image. My app is written on vue.js, so I am going to put bootstrap code into vueJS.
In my idea in the tooltip it should be written the description of the economic term (src_russian) or the Russian name of this term (src_chinese). But in reality, tooltip tells me "gameprop.name" and "gameprop.description" only.
Here is my code:
HTML:
<div id="game"> <ol> <game-card v-for="card in cardList" v-bind:gameprop="card" v-bind:key="card.id"> </game-card> </ol> </div>JS:
Vue.component('game-card', { props: ['gameprop'], template: '<span><a href="#" data-toggle="tooltip" title="gameprop.name"><img :src = "gameprop.src_chinese" /></a><a href="#" data-toggle="tooltip" title="gameprop.description"><img :src = "gameprop.src_russian" /></a></span>' }) var game = new Vue({ el: '#game', data: { cardList: [ { id: 0, src_chinese: 'img/actions/actions_chinese.jpg', src_russian: 'img/actions/actions_russian.jpg', name: "Акция", description: "Акция – ценная бумага, свидетельствующая о внесении средств в капитал акционерного общества и дающая право на получение части прибыли в виде дивидендов" }, { id: 17, src_chinese: 'img/vexel/vexel_chinese.jpg', src_russian: 'img/vexel/vexel_russian.jpg', name: "Вексель", description: "Вексель — ценная бумага, оформленная по строго установленной форме, удостоверяющая перетекание одного обязательства в другое обязательство и дающая право лицу, которому вексель передан на основании соответствующего договора, на получение от должника определённой в векселе суммы" }, ] } }) Vue.directive('tooltip', function(el, binding){ $(el).tooltip({ title: binding.value, placement: binding.arg, trigger: 'hover' })Where is my mistake?
VueJS Toggle class to specific element in table
I can’t seem to figure out how to toggle a class on a specific item in a table. I’m using v-for to loop over the data and printing it out to the user. The goal is to toggle a class when the user clicks on a specific element inside the table. When i’m trying to add a v-bind:class="{'active' : isActive} it just adds that class to all of them and not the specific.
<table> <tbody> <tr v-for="(item, index) in tableFilter" @click="selectThis(item)" v-bind:class="{'active': isActive}"> <td>{{item.Name}}</td> <td>{{item.Address}}</td> <td>{{item.Telephone}}</td> <td>{{item.Email}}</td> </tr> </tbody> </table> export default { data() { return { isActive: false, data: data } }, methods: { selectThis(val, index) { this.isActive =! this.isActive } }, computed: { tableFilter() { return data; } }Set focus on input after it's showed by v-show
I have a simple form that is hidden when the page is loaded, using v-show. I want to focus the input after showing it. I have a button to call a a method that shows the form and sets the focus to the input using this code:
this.newQuestion = true; //(Form whit v-show:newQuestion) this.$refs.questionInput.focus();The problem is that the form is showed correctly, but the input isn't focused the first time I press the button, if I press it for a second time when the form is in the page it works. I want to know if there is a way to do this, thanks.
Security of changing password in vue's component
I made an component in my SPA application to changing user's password. All my code that is working correctly looks like this:
method which is getting data from form with v-model:
export default { data(){ return { password: { old_password: '', new_password: '', repeat_password: '' } } }, methods: { changePassword() { axios.post('api/change_password', this.password).then( response=> { this.password = { old_password: '', new_password: '', repeat_password: '' }; console.log(response.data.message); }); } } }then in my controller i receive data and I am validating them in this way:
public function update(Request $request) { $get_user = Auth::user(); $user = User::find($get_user->id); $current_password = $get_user->password; if (Hash::check($request->input('old_password'), $get_user->password) && ($request->input('new_password') == $request->input('repeat_password'))) { $user->update([ 'password' => Hash::make($request->input('new_password')) ]); return response()->json([ 'message' => 'Password updated' ]); } }My question to you guys is that: Is this method secure? If not could you explain how to do this in better way?
authentication system using token in nodejs vuejs app?
I have built an spa using nodejs and vuejs i want to add an authentication system on it, but i haven't done it before hence need some guidance.
the flow will be like : 1) admin will create the profile of the user 2) An email will be automatically sent to the user using sendgrid 3) the email consits of an url with token which expires in 24 hrs the user when click in specific time will be routed to a page where they can create a new password 4) i was planning to use passport for authentication in my app
Is this the right way to do?, also how do i send the token with url and authenticate when i the user clicks
The Battle to Save Net Neutrality: A Panel with Tom Wheeler, Ro Khanna, Mozilla, Leading TV Producers and Others
Net neutrality — and the future of a healthy internet — is at stake.
In May, the FCC voted to move forward with plans to gut net neutrality. It was a decision met with furor: Since then, many millions of Americans have written, phoned and petitioned the FCC, demanding an internet that belongs to individual users, not broadband ISP gatekeepers. And scores of nonprofits and technology companies have organized to amplify Americans’ voices.
The first net neutrality public comment period ends on August 30, and the FCC is moving closer to a vote.
So on Monday, September 18, Mozilla is gathering leaders at the forefront of protecting net neutrality. We’ll discuss why it matters, what lies ahead, and what can be done to protect it.
RSVP: The Battle to Save Net Neutrality
Leaders like former FCC Chairman Tom Wheeler and Congressman Ro Khanna will discuss net neutrality’s importance to free speech, innovation, competition and social justice.
This free public event, titled “Battle to Save Net Neutrality,” will feature a panel discussion, reception and audience Q&A. It will be held at the Internet Archive (300 Funston Avenue, San Francisco) from 6 p.m. to 9 p.m. Participants include:
- Panelist Tom Wheeler, former FCC Chairman who served under President Obama and architect of the 2015 net neutrality rules
- Panelist and Congressman Ro Khanna (D-California), who represents California’s 17th congressional district in the heart of Silicon Valley. Khanna is a vocal supporter of net neutrality
- Panelist Amy Aniobi, TV writer and producer for “Insecure” (HBO) and “Silicon Valley” (HBO), and member of the Writers Guild of America, West
- Panelist Luisa Leschin, TV writer and producer for “From Dusk til Dawn” (Netflix) and “Just Add Magic” (Amazon), and a member of the Writers Guild of America, West
- Panelist Denelle Dixon, Mozilla Chief Legal and Business Officer. Dixon spearheads Mozilla’s business, policy and legal activities in defense of a healthy internet. She is a vocal advocate for net neutrality, encryption and greater user choice and control online
- Panelist Malkia Cyril, Executive Director of the Center for Media Justice. Cyril has spent the past 20 years building the capacity of racial and economic justice movements to win media rights, access and power in the digital age
- Moderator Gigi Sohn, Mozilla Tech Policy Fellow and former counselor to FCC Chairman Tom Wheeler (2013-2016). One of the nation’s leading advocates for an open, fair, and fast internet, Sohn was named “one of the heroes that saved the Internet” by The Daily Dot for her leadership in the passage of the FCC’s strong net neutrality rules in 2015
Join us as we discuss the future of net neutrality, and what it means for the health of the internet. Register for this free event here.
The post The Battle to Save Net Neutrality: A Panel with Tom Wheeler, Ro Khanna, Mozilla, Leading TV Producers and Others appeared first on The Mozilla Blog.
Vue wait until all images referenced in CSS have loaded
In my Vue app I have a large image (170K) that is referenced in CSS as a background image. While my app is initially loading, I would like to show a spinner image or div that waits until this image has finished loading. This seems to be the default behavior in Angular2+, how do I achieve the same with Vue?
Load PDF in modal with Laravel routes and vuejs axios
I am trying to generate a PDF and open a modal on button click. In the modal the generated PDF should be loaded in the DOM.
To generate the PDF I use axios:
axios.post('/preview', formData) .then(function (response) { this.previewPdf = response.data; }.bind(this));The generated PDF name is returned in the controller and saved in the this.previewPdf variable.
Then I use laravel URL wildcards to load the PDF in the modal.
<div class="modal-body"> <embed :src="'/preview/' + previewPdf" width="100%" height="600" type='application/pdf'> </div>And the controller for the route /preview/{pdfname} returns the PDF.
return Storage::disk('local')->get('temppdf/' . $pdfname);However if I open the modal the PDF seems to be loaded (Network preview):
%PDF-1.7 %���� 2 0 obj <</Type/XObject etc.
But the modal just shows an empty <embed>. Although the src of it is correctly src="preview/pdfname.pdf".
What could cause this issue?
Filtering data with forms and Vuex without conditionals
In my component I am looping through a list of items:
<item v-for="item in items" :key="item.id" :item="item"> </item>I have a getter which based on filter criteria sets state.items:
export const items = state => state.items.filter(item => item.mySex === state.filter);These are the filter radio buttons:
<input class="form-check-input" type="radio" name="sexFilter" v-model="mySex" id="sex-female" value="1">And I use watch to dispatch actions:
watch: { mySex(value) { this.$store.dispatch('setFilter', Number(value)); }, },My problem is that when no filter is applied my getter sends back 0 results. I would like to tackle that without using conditions.
How to listen to scroll event in a Vue component?
I can't find a way to actually listen to a scroll event in my component. I tried v-on:scroll="scrollFunction" but it doesn't seem to work.
Does anyone know how to do it?
Thanks!