Software

Getting a firebase object's key after it has been passed down as a prop in Vue

Vuejs - Fri, 2017-09-01 02:24

I am new to Firebase. I have a thought schema in the firebase database like this:

{ title: "I should learn VueJS + Firebase", body: "With VueJS+Firebase, I can take over the worlddd! Here's how I'll do it..." }

Using the ListOfThoughts.vue component, we can render our thoughts to our template like this:

<template> <div class="list-of-thoughts"> <ThoughtItem v-for="thought in thoughts" :thought="thought" /> </div> </template> <script> import firebase from './../firebase' import ThoughtItem from './ThoughtItem.vue' export default { components: { ThoughtItem }, data () { return { thoughts: [] } }, created() { const thoughtsRef = firebase.database().ref().child('thoughts'); thoughtsRef.on('value', snapshot => { this.thoughts = snapshot.val(); }, errorObject => { console.log('Error retrieving thoughts: ' + errorObject.code); }) } } </script>

Notice that we are using the ThoughtItem component which looks like this:

<template> <div class="thought"> <h1>{{thought.title}}</h1> <p>{{thought.body}}</p> </div> </template> <script> import firebase from './firebase' export default { props: ['thought'], methods: { getThoughtKey() { // How can we access the Key of this particular `thought` here? // I need the key value to access the database object. Like this: firebase.database().ref().child(key); } } } </script>

(Please check out the comments)

I am hoping to access the Key of this thought object so that I may update it. How can I do this?

Categories: Software

Javascript: (How) can you use filter to search in multiple key values of objects in an array?

Vuejs - Fri, 2017-09-01 01:07

I have an array of Wines containing an object with data for each wine:

var wines = [ { _id: '59a740b8aa06e549918b1fda', wineryName: 'Some Winery', wineName: 'Pinot Noir', wineColor: 'Red', imageLink: '/img/FortBerensPN.png' }, { _id: '59a7410aaa06e549918b1fdb', wineryName: 'Some Winery', wineName: 'Pinot Gris', wineColor: 'White', imageLink: '/img/FortBerensPG.png' }, { _id: '59a74125aa06e549918b1fdc', wineryName: 'Some Winery', wineName: 'Rose', wineColor: 'Rose', imageLink: '/img/FortBerensRose.png' }, { _id: '59a74159aa06e549918b1fdd', wineryName: 'Some other Winery', wineName: 'Rose', wineColor: 'Rose', imageLink: '/img/FortBerensRose.png' }, { _id: '59a7417aaa06e549918b1fde', wineryName: 'Some other Winery', wineName: 'Pinot Gris', wineColor: 'White', imageLink: '/img/FortBerensPG.png' }, { _id: '59a8721f4fd43b676a1f5f0d', wineryName: 'Some other Winery', wineName: 'Pinot Gris', wineColor: 'White', imageLink: '/img/FortBerensPG.png' }, { _id: '59a872244fd43b676a1f5f0e', wineryName: 'Winery 3', wineName: 'Pinot Noir', wineColor: 'Red', imageLink: '/img/FortBerensPN.png' } ]

I can figure out how to search for a wine object while specifying which key of the object to search in like this: (need to use toLowerCase as var search will be user input)

var search = 'Noir' filteredWines = function () { return wines.filter(function(wine){ return (wine.wineName.toLowerCase().indexOf(search.toLowerCase())>=0 }) // returns: // [ { _id: '59a740b8aa06e549918b1fda', // wineryName: 'Some Winery', // wineName: 'Pinot Noir', // wineColor: 'Red', // imageLink: '/img/FortBerensPN.png' }, // { _id: '59a872244fd43b676a1f5f0e', // wineryName: 'Winery 3', // wineName: 'Pinot Noir', // wineColor: 'Red', // imageLink: '/img/FortBerensPN.png' } ]

However, if var search = 'Winery 3' or var search = 'red' then it will obviously return no results as it's looking in the value of wineName of each object in the array.

So is there a way to use filter (or another method?) to search through all key values, or even better multiple specified key values and return an array of the matching objects?

Something like:

filteredWines = function () { return wines.filter(function(wine){ return ((wine.wineName.toLowerCase() && wine.wineName.toLowerCase() && wine.wineName.toLowerCase()).indexOf(search.toLowerCase())>=0 })

Or am I completely barking up the wrong tree?!

PS. I'm using Vue.js 2 so if there's a better way inside vue then I'm all ears!

Thank you!

Categories: Software

Building a form with inline editing

Vuejs - Fri, 2017-09-01 01:01

Let's say we have rendered the following template which represents a book:

<div class="book"> <h1 class="book__title" ref="title">{{book.title}}</h1> <p class="book__description">{{book.description}}</p> <button @click="activateEditMode">Edit Book</button> </div>

I would like to allow my users to quickly edit this book. When users click the Edit Book button, they should be able to edit inline. It is as if the .book card is replaced by a form. It is similar to how Facebook allow its users to edit comments inline.

I have tried replacing the <h1> and <p> elements with a corresponding <input> and <textarea> elements programatically in the activateEditMode() method:

activateEditMode() { let bookTitle = this.$refs.title; let bookTitleInput = document.createElement('input'); // but how do we programatically attach the v-model="book.title" // binding to our newly created input element here? bookTitleInput.value = this.book.title; }

How would we attach our v-model binding to our newly created input element using JavaScript?

Is this the best approach to do this?

Categories: Software

Getting the highest value of an JSON array and storing it in Data Vue

Vuejs - Fri, 2017-09-01 00:44

In my vue component i have a json array of Bids.

enter image description here

I need to get the highest bid from the array and store it into another variable.

My vue component data:

data() { return { bids: [], bid: null, veiling_id: this.id, showInput: this.auth_check, highestBid: null, } },

Getting the bids from DB and storing into bids.

mounted(){ var veilingid = this.veiling_id; var vm = this; setInterval(function(){ axios.get('/veilingen/' + veilingid + '/getbid'). then(function (response){ vm.bids = response.data; }).catch(function(error) { console.log(error); }); }, 1000); }

And now how do i loop through Bids, get the highest bid and store it into highestBid?

Also what's the best place to store the code?

Right after the AXIOS get request in the mounted() or somewhere else?

I'm sorry i'n new to Vue.

Any help is appreciated..

Categories: Software

Fire vue method from jquery on click event

Vuejs - Thu, 2017-08-31 23:45

I'm trying to append a click event to an already existing dom element.

<div class="logMe" data-log-id="{{ data.log }}"></div> ... <div id="events"></div>

I can't seem to access outside vue methods within my jquery click handler. It will throw logData is not defined.

new Vue({ el: '#events', mounted() { $('.logMe').on('click', function() { const data = $(this).data('log-id'); this.logData(data); // throws logData is not defined }); }, methods: { logData(id) { console.log(id); // never fires ... hit server }, }, });

If anyone knows of a better way to append click events to .html elements that would be great! But how can I bubble up and find my vue methods? Here's a fiddle to illustrate

Categories: Software

Data not passing in axios post request

Vuejs - Thu, 2017-08-31 23:31

I'm using axios to call a post request as follows:

axios.post(this.api+'&action='+this.action+'&wftkn='+this.wftkn, {name: 'Abcd'}). then((res)=>{ });

When I check the network tab, I don't see the data being passed in the Request header. What would be the issue in this case?

Categories: Software

Use Vue variable in style section of a component

Vuejs - Thu, 2017-08-31 23:02

Is it possible to use a variable with the style tag of a component? Basically I have imported a mixin to my style tag that accepts 2 colors to create a gradient within a class. It works great but I want this dynamic so I can set it via a database. I understand I can bind a style via inline but a gradient for a div is rather long and works way better as a mixin.

component:

<template> <section class="section" v-bind:class=" { 'color-section' : content.gradient_color_one }"> <div class="container"> <div class="columns"> <div class="column is-half"> <h2 class="is-size-4" v-html="content.title"></h2> <div class="section-content" v-html="content.description"></div> <a class="button" :href=" '/'+ content.button_link">{{ content.button_text }}</a> </div> <div class="column"> <img :src="content.image" :alt="content.title" /> </div> </div> </div> </section> </template> <script> export default { props:[ 'content' ], } </script> <style lang="scss" scoped> @import "../../sass/helpers/mixins"; .color-section{ color:red; @include diagonalGradient( content.gradient_color_one , content.gradient_color_two); } </style>

mixins

@mixin diagonalGradient($top, $bottom){ background: $top; background: -moz-linear-gradient(-45deg, $top 0%, $bottom 100%); background: -webkit-gradient(left top, right bottom, color-stop(0%, $top), color-stop(100%, $bottom)); background: -webkit-linear-gradient(-45deg, $top 0%, $bottom 100%); background: -o-linear-gradient(-45deg, $top 0%, $bottom 100%); background: -ms-linear-gradient(-45deg, $top 0%, $bottom 100%); background: linear-gradient(135deg, $top 0%, $bottom 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#92fe9d', endColorstr='#00c8ff', GradientType=1 ); }
Categories: Software

Programatically change the value of the @click method

Vuejs - Thu, 2017-08-31 21:57

Here is an element with a @click handler:

<button @click="doSomething">doSomething</button>

Inside this element, how can we programatically change the value of doSomething with doSomethingElse?

Categories: Software

Vue.js template concatenate props

Vuejs - Thu, 2017-08-31 21:22

JS:

Vue.component('profile', { template: `<a v-bind:href="id"></a>`, props: ['id'] }); var app = new Vue({ el: '.app', data: { user: userobject } });

HTML:

<profile :id="user.id"></profile>

Expected result:

<a href="/profile/2">

Question: How to concatenate "/profile/" with user.id that is equal to 2?

Categories: Software

VueJs component undefined

Vuejs - Thu, 2017-08-31 20:49

I am new to . The component, comp1 doesn't appear to work.

HTML

<div id="example-2"> <comp1></comp1> </div>

Script

var data1={selected: null, items:["degradant", "impurity"]}; Vue.component('comp1, { template:'<select v-model="selected"> <option disabled value="">Please select</option> <option v-for="item in items" :value="item">{{item}}</option> </select>', data: function(){ return data1 } }); new Vue({ el: '#example-2' })
Categories: Software

How to call getter function inside getter function in Vuex

Vuejs - Thu, 2017-08-31 20:27
import Vue from 'vue' import Vuex from 'vuex' import { createModule } from 'vuex-toast' import 'vuex-toast/dist/vuex-toast.css' Vue.use(Vuex) const store = new Vuex.Store({ modules: { toast: createModule({ dismissInterval: 80000 }), app: { state: { raps: [], }, getters: { getRaps () { return store.state.app.raps }, getRapsFiltered (state, getters) { //error happens in this func return getters.getRaps.filter(state.filterFunc) } } } } }) export default store

I got error message "Uncaught TypeError: null is not a function". How to call getter function inside getter? What seems to be problem with this code?

Categories: Software

Nested select box issue changing the first one

Vuejs - Thu, 2017-08-31 18:54

I am building some logic ith 2 nested select box, basicly i load a json file and pass the data to an array in my vuejs component, the json contains the logic for the 2 select box for example for Business Developemnt i want to load in the second box Financial Proposal and Master Licence...:

{ "Business Development": [ { "text": "Financial Proposal", "key": 1 }, { "text": "Master Licence and Service Agreement", "key": 2 }, { "text": "Non-Disclosure Agreement", "key": 3 }, { "text": "Relatório de Missão", "key": 4 } ], "Configuration Management": [ { "text": "Configuration Management Plan", "key": 1 }, { "text": "Configuration Management Plan For Implementation Projects", "key": 2 }

I already accomplish something like that, the issue is that when i change the first select box, the second is empty at position 1, like this:

image

here is my code:

<template> <div class="row margin-above2 box"> <h3 class="text-center">Template</h3> <img width="70px" height="70px" class="img img-responsive" src="static/img/word.png"> <form class="box-body form-horizontal"> <div class="form-group"> <div class="col-sm-12"> <select class="form-control" v-model="docData.documentType"> <option v-for="(item,index) in documentNested"> {{ index }} </option> </select> </div> </div> <div class="form-group"> <div class="col-sm-12"> <select class="form-control" v-model="docData.documentSelection"> <option v-for="(item,index) in documentNested[docData.documentType]">{{item.text}}</option> </select> </div> </div> </form> </div> </template> <script> import data from '../../interfaceData/documentType.json' import permissions from '../../interfaceData/permissions.json' export default { name: 'app', data () { return { checked: false, documentNested: data, permissions: permissions, listItems: [], documentData: [] } },

thank you! :)

Categories: Software

How to authenticate to google OAuth2 in Vue.js?

Vuejs - Thu, 2017-08-31 18:45

As a beginner to vue.js I'm struggling with this problem for days. I know that there are few plugins for that:

vue-google-auth

and

vue-google-signin-button

and

vue-authenticate

But none of these come with good documentations, so my attempts to make use of them failed. I also could not find any tutorial on vue.js with OAuth2 authentication after extensive googling. So appreciate if someone could come up with a full working example or refer me to some complete code.

Categories: Software

VeeValidate localization "Property 'locale' does not exist on type 'Validator'."

Vuejs - Thu, 2017-08-31 18:38

I'm using VeeValidate and works perfectly for English (which is default) however if I try to use any other language I'm getting an error saying "Property 'locale' does not exist on type 'Validator'."

Here is my code:

import VeeValidate from 'vee-validate'; import french from 'vee-validate/dist/locale/fr'; Vue.use(VeeValidate); @Component export default class TestTest extends Vue { locale: any; // I have tried locale: string='fr'; nextLocale() { return this.locale === 'en' ? 'French' : 'English'; } changeLocale() { this.locale = this.$validator.locale === 'fr' ? 'en' : 'fr'; this.$validator.setLocale(this.locale); } created() { this.$validator.updateDictionary({ fr: { messages: french.messages, } }) } // other none related code... }
Categories: Software

how to stop commited mutation in Vuex

Vuejs - Thu, 2017-08-31 17:45

Is there any way in vuex to stop a mutation after commit? For redux, if next is not called in middleware, then we can say that the action is stopped

Categories: Software

Getting input field values from Form submit using Vue

Vuejs - Thu, 2017-08-31 17:22

I have a form with 1 input field that i want to shoot into the database. I am using Vue.

Template:

<form class="form-horizontal" @submit.prevent="submitBid"> <div class="form-group"> <label for="bid"></label> <input name="bid" type="text"> </div> <div class="form-group"> <input class="btn btn-success" type="submit" value="Bieden!"> </div> </form>

Component:

export default { props: ['veiling_id'], methods: { submitBid(event) { console.log(event); }, }, computed: { }, mounted(){ } }

How do i get the value of the input field inside submitBid function?

Any help is appreciated.

Categories: Software

Vuelidate: validate on click, not when field touched (Vue.js)

Vuejs - Thu, 2017-08-31 16:35

I'm kinda new to vuelidate, and everything works fine, except I have no clue how to run validation only when the button 'submit' has been clicked. Right now it marks touched field red when you start providing any input and I'd like it to wait with that till user wants to submit filled form.

Here's what I've got up to now:

Vue.use(window.vuelidate.default) const { required, minLength, sameAs } = window.validators new Vue({ el: "#app", data: { user: { login: '', password: '', repeatedPassword: '' } }, validations: { user: { login: { required, minLength: minLength(5) }, password: { required, minLength: minLength(8) }, repeatedPassword: { required, sameAs: sameAs('password') } } } }) input { border: 1px solid silver; border-radius: 4px; background: white; padding: 5px 10px; } .error { border-color: red; background: #FDD; } .error:focus { outline-color: #F99; } .valid { border-color: #5A5; background: #EFE; } .valid:focus { outline-color: #8E8; } <script src="https://unpkg.com/vue"></script> <script src="https://unpkg.com/vuelidate/dist/validators.min.js"></script> <script src="https://unpkg.com/vuelidate/dist/vuelidate.min.js"></script> `<div id="app"> <input type="text" placeholder="login" v-model="user.login" v-on:input="$v.user.login.$touch" v-bind:class="{error: $v.user.login.$error, valid: $v.user.login.$dirty && !$v.user.login.$invalid}"> <br/> <input type="password" placeholder="password" v-model="user.password" v-on:input="$v.user.password.$touch" v-bind:class="{error: $v.user.password.$error, valid: $v.user.password.$dirty && !$v.user.password.$invalid}"> <br/> <input type="password" placeholder="repeat password" v-model="user.repeatedPassword" v-on:input="$v.user.repeatedPassword.$touch" v-bind:class="{error: $v.user.repeatedPassword.$error, valid: $v.user.repeatedPassword.$dirty && !$v.user.repeatedPassword.$invalid}" > <button :disabled="$v.user.$error" @click="$v.user.$touch()"> Submit! </button> </div>`

Please, be gentle :D It's first time when I got courage to ask anything here ^^

Categories: Software

Vue.js change template data

Vuejs - Thu, 2017-08-31 16:04

I have the following code:

Vue.component('greeting', { template: `<h1>{{ greeting }}</h1>`, data: function () { return { greeting: app.text } }, }); var app = new Vue({ el: '.app', data: { text: 'Hello' }, methods: { changeText: function () { this.text = 'Goodbye' } } });

So when I call changeText method it changes text but greeting in the component is not updated. I didn't understand if I should use props, watcher or computed property in this case.

Categories: Software

Why does vue.js execution not fire beforeUpdate, updated, and activated events?

Vuejs - Thu, 2017-08-31 15:48

What does this vue.js code execute:

  • beforeCreate
  • created
  • mounted

but not:

  • beforeUpdate
  • updated
  • activated

https://jsfiddle.net/edwardtanguay/3hkdbuke

var vm = new Vue({ el: '#app', data: function() { return { message: 'This is a test.' } }, methods: { changeText: function() { this.message = 'changed'; } }, beforeCreate: function() { this.$nextTick(() => { console.log('in beforeCreate'); // gets here }); }, created: function() { this.$nextTick(() => { console.log('in created'); // gets here }); }, mounted: function() { this.$nextTick(() => { console.log('in mounted'); // gets here }); }, beforeUpdate: function() { this.$nextTick(() => { console.log('in beforeUpdate'); //DOESN'T GET HERE }); }, updated: function() { this.$nextTick(() => { console.log('in updated'); //DOESN'T GET HERE }); }, activated: function() { this.$nextTick(() => { console.log('in activated'); //DOESN'T GET HERE }); } });
Categories: Software

npm error:A valid query string passed to parseQuery should begin with '?'

Vuejs - Thu, 2017-08-31 14:59

Once I run npm run buildin my vue2 project,an error explained thatloaderUtils.getOptions is not a function.

After I cnpm install vue-loader vue-template-compiler loader-utils ,the following error occurred:

ERROR in Error: Child compilation failed: Module build failed: Error: A valid query string passed to parseQuery should b egin with '?' - parseQuery.js:13 Object.parseQuery [cg.test]/[_loader-utils@1.1.0@loader-utils]/lib/parseQuery.js:13:9 - Error: A valid query string passed to parseQuery should begin with '?' - compiler.js:76 [cg.test]/[html-webpack-plugin]/lib/compiler.js:76:16 - Compiler.js:296 Compiler.<anonymous> [cg.test]/[webpack]/lib/Compiler.js:296:10 - Compiler.js:499 [cg.test]/[webpack]/lib/Compiler.js:499:13 - Tapable.js:202 next [cg.test]/[tapable]/lib/Tapable.js:202:11 - CachePlugin.js:62 Compiler.<anonymous> [cg.test]/[webpack]/lib/CachePlugin.js:62:5 …… …… ERROR in ./src/main.js Module build failed: Error: A valid query string passed to parseQuery should begin with '?' at Object.parseQuery (D:\***\node_modules\_loader-utils@1.1.0@loader-utils\lib\parseQuery.js:13:9) at Object.module.exports (D:***\node_modules\_babel-loader@6.4.1@babel-loader\lib\index.js:104:35) Build complete. Tip: built files are meant to be served over an HTTP server. Opening index.html over file:// won't work.

I used to update the version of the babel-loader,vue-cli,vue-loader, vue-template-compiler,loader-utils,webpackornpm install,but none of them work.Does anybody know the problem?

Categories: Software

Pages