link1644 link1645 link1646 link1647 link1648 link1649 link1650 link1651 link1652 link1653 link1654 link1655 link1656 link1657 link1658 link1659 link1660 link1661 link1662 link1663 link1664 link1665 link1666 link1667 link1668 link1669 link1670 link1671 link1672 link1673 link1674 link1675 link1676 link1677 link1678 link1679 link1680 link1681 link1682 link1683 link1684 link1685 link1686 link1687 link1688 link1689 link1690 link1691 link1692 link1693 link1694 link1695 link1696 link1697 link1698 link1699 link1700 link1701 link1702 link1703 link1704 link1705 link1706 link1707 link1708 link1709 link1710 link1711 link1712 link1713 link1714 link1715 link1716 link1717 link1718 link1719 link1720 link1721 link1722 link1723 link1724 link1725 link1726 link1727 link1728 link1729 link1730 link1731 link1732 link1733 link1734 link1735 link1736 link1737 link1738 link1739 link1740 link1741 link1742 link1743 link1744 link1745 link1746 link1747 link1748 link1749 link1750 link1751 link1752 link1753 link1754 link1755 link1756 link1757 link1758 link1759 link1760 link1761 link1762 link1763 link1764 link1765 link1766 link1767 link1768 link1769 link1770 link1771 link1772 link1773 link1774 link1775 link1776 link1777 link1778 link1779 link1780

[Vue.js] Using Vuex data right after setting them

So, there is a page with a form where a user can edit its account information (just the name here). The idea is that the form is prefilled with the current data. If I arrive on the page after the passing through the login screen, I can use the data in the store to prefill the form. But, if I access directly the page, the store is empty. So, what I tried is triggering an action in the created hook to populate the store and then use those data.

<template>
<div>
<navbar></navbar>
<div class=”container”>
<div class=”columns”>
<div class=”column is-4 is-offset-4”>
<h1 class=”title”>Update information</h1>

<div class=”field”>
<label class=”label is-medium”>Name</label>
<div class=”control has-icons-left”>
<input class=”input is-medium” type=”text” v-model=”name” placeholder=”John”>
<span class=”icon is-small is-left”>
<font-awesome-icon icon=”user” />
</span>
</div>
</div>

<div class=”control”>
<button class=”button is-primary” v-bind:class=”{ ‘is-loading’: isLoading }” @click=”updateInfo”>Update</button>
</div>

<transition name=”fade”>
<div v-show=”succesAlert” class=”notification is-primary”>
The update is a success
</div>
</transition>
</div>
</div>
</div>
</div>
</template>

<script>
import firebase from ‘firebase’
import { mapState, mapActions } from ‘vuex’

import Navbar from ‘@/components/layout/Navbar’

export default {
name: ‘profile’,
components: {
Navbar
},
data() {
return {
name: ‘’,
isLoading: false,
succesAlert: false,
};
},
methods: {
…mapActions([‘setUser’, ‘updateUser’]),
updateInfo: function() {
this.isLoading = true;

const user = {
name: this.name
}

this.updateUser(user, firebase.auth().currentUser.uid).then(() => {
this.isLoading = false;
this.succesAlert = true;
setTimeout(() => { this.succesAlert = false; }, 3000);
});
}
},
computed: {
…mapState([‘userInfo’])
},
created: function() {
if(typeof userInfo == ‘undefined’) {
this.setUser(firebase.auth().currentUser.uid).then(() => {
this.name = userInfo.name; //Where the error occurs
});
} else {
this.name = userInfo.name;
}
}
}
</script>

But, when I do so, I still have an error Unhandled promise rejection ReferenceError: “userInfo is not defined”. So I suppose the status of the store is not updated in the component. However I don’t really see how I could get around.

Solution :

It’s because you didn’t return anything from promise.
Change you code:

this.setUser(firebase.auth().currentUser.uid).then(res => {
this.name = res.userInfo.name;
});

Be sure that response returns property “userInfo”. It could be res.data.userInfo or something like this.

You can check that exactly the promise returns using console.log

this.setUser(firebase.auth().currentUser.uid).then(res => {
console.log(res) // check browser’s console
this.name = res.userInfo.name;
});

[Vue.js] Get all list from one firestore collection with VueJS

to display all user list by firestore query.
But I stuck at promise chain.
To query documents of collection, two asyncronous steps needed. How can I get wait until fill all list set.

Here is my code. I hope my fetchUsers() fill array without call back chain.

const db = firebase.firestore();

export default {
data: () => {
return {
users: [],
}
},
mounted: function() {
this.fetchUsers()
console.info(‘mounted, users:’, this.users) // // => at this point, this.users is not yet ready.
},
computed: {
items: function() {
return this.users
}
},
methods: {
async fetchUsers () {
await db.collection(‘users’).get()
.then(snapshot => {
snapshot.forEach( doc => {
const user = doc.data()
console.log(‘forEarch:’ , user)
user.id = doc.id
this.users.push(user)
})
})
.catch(error => {
console.error(error)
})
console.debug(‘fetchUser return: ‘, this.users) // => at this point, this.users is not yet ready.
},

Solution :

Don’t mix async/await syntax with then/catch

const query = db.collection(‘users’)

async fetchUsers () {
try {
const { docs } = await query.get()

this.users = docs.map(doc => {
const { id } = doc
const data = doc.data()
return { id, …data }
})

console.log(‘Loaded users’, this.users)
} catch (error) { throw new Error(‘Something gone wrong!’) }
}

[Vue.js] How to nest object data in Vue CLI3 with Typescript?

In plain js we could write:

data() {
return {
form: {
name: ‘’,
password: ‘’
}
}
}

But how to achieve this using typescript (vue-property-decorator)? I’ve read this should be implemented using interfaces, like that:

interface Form {
name: string
password: string
}

@Component
export default class Login extends vue.js {
// how to use interface here?
}

I’m using this as v-model on input:

<input v-model=”form.email”>

Solution :

the class component can have a property form which is of type Form

interface Form {
name: string
password: string
}

@Component
export default class Login extends vue.js {
form:Form = {name: ‘’, password: ‘’}
}

Didn’t test this though!

EDIT

An example of an interface that uses interfaces itself

interface Form {
users : User[]
password : string
}

interface User {
name : string
id : number
}

let form : Form = {
users: [
{ name:”Ren”, id:3 },
{ name:”Stimpy”, id:43 }
],
password: ‘’
}

[Vue.js] Vue Axios CORS policy No 'Access-Control-Allow-Origin'

I build an app use vue.js and codeigniter, but there is a problem when I try to get api, I got this error on console

Access to XMLHttpRequest at ‘http://localhost:8888/project/login'
from origin ‘http://localhost:8080' has been blocked by CORS policy:
Request header field access-control-allow-origin is not allowed
by Access-Control-Allow-Headers in preflight response.

there is been try like this on front-end (main.js)

axios.defaults.headers.common[‘Content-Type’] = ‘application/x-www-form-urlencoded’
axios.defaults.headers.common[‘Access-Control-Allow-Origin’] = ‘*‘;

and this on backend (controller)

header(‘Access-Control-Allow-Origin: *‘);
header(“Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE”);

and vue.js login method

this.axios.post(‘http://localhost:8888/project/login', this.data, {
headers: {
“Access-Control-Allow-Origin”: “*“,
“Access-Control-Allow-Methods”: “GET, POST, PATCH, PUT, DELETE, OPTIONS”,
“Access-Control-Allow-Headers”: “Origin, Content-Type, X-Auth-Token”
}
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err.response);
});

I’ve searched and tried in stackoverflow but does not work, how I can solve it? thank you so much for the help

Solution :

CORS is the server telling the client what kind of HTTP requests the client is allowed to make. Anytime you see a Access-Control-Allow-* header, those should be sent by the server, NOT the client. The server is “allowing” the client to send certain headers. It doesn’t make sense for the client to give itself permission. So remove these headers from the frontend code.

axios.defaults.headers.common[‘Access-Control-Allow-Origin’] = ‘*‘;

this.axios.post(‘http://localhost:8888/project/login', this.data, {
headers: {
// remove headers
}
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err.response);
});

For example, imagine the backend set this cors header.

header(“Access-Control-Allow-Methods: GET”);

That means a client from a different origin is only allowed to send GET requests, so axios.get would work, axios.post would fail, axios.delete would fail, etc.

[Vue.js] VueJS refresh content after database operation

I’m using a v-data-table component to display data from firestore database. It looks something like this:

The approve/disapprove functionality works well, updating the firestore database with the below code:

database
.collection(member)
.doc(userId)
.update({
approved: status
})
.then({
console.log(“School member details updated successfully”)
return this.teachers.filter(teacher => {
return teacher.id != userId;
});
})
.catch(err => {
console.log(
“An error occured trying to update the school member details:”,
err
);
});

However, after the content is updated successfully on firestore database I no longer want to show the list item, I thought filtering the array as there is done in the then() code block would work but its not.

How could I refresh the data for the client without reloading the whole page again?

Solution :

You mentioned that you don’t want to show the particular list Item after successful approved. As you used teacher.id != userId. Have you used teacher.id !== userId?

[Vue.js] Image does not uploaded in vue-codeigniter

I build an app use vue.js and codeigniter rest server, I try to upload file by postman and it’s work fine, but when I try from front-end, file is not uploaded, folder permission has been allowed, this is my vue.js code

data() {
return {
data: {
photo: // base64 data
}
}
}

on methods

addMember(){
this.axios.post(‘member’, this.data).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
}

on back end

$filename = round(microtime(true)).’.png’;
$config[‘file_name’] = $filename;
$config[‘upload_path’] = ‘./storage/‘;
$config[‘allowed_types’] = ‘*‘;
$config[‘max_size’] = 50000;
$config[‘max_width’] = 50000;
$config[‘max_height’] = 50000;

$this->load->library(‘upload’, $config);
$this->upload->do_upload(‘photo’);

thanks for the response

Solution :

I think if you success get the send but without file, maybe the send type has error
For server Base64 is a String ,not a file(byte stream) ,for axios ,default send type is Application/json, and it only can not send a Byte Stream , so you should cheack the server can get a String and transform to file
But if the server want a file , you should use formData
And I suggest you use FormData to send file
Here is a examples for you if you want use axios send formData.

let formData = new FormData();
formData.append(photo,this.photo);
this.$axios({
url: ‘/member’,
method: ‘post’,
data: formData
});

[Vue.js] How to call a method from a different file using event bus

in CreateEntryStepper.vue.js there is a button that that when pressed calls a function to activate in CreateEntryStepperImageUpload.vue

i know there is to use event busses but i really have no idea what i need to pass in and how to get them working

bus.js just has

import vue.js from “vue”;

export const bus = new Vue();

CreateEntryStepper.vue.js (not sure what to emit here)

import { bus } from “@/components/wizard/bus.js”;

async submitEntry() {

this.$Progress.start();
bus.$emit();

CreateEntryStepperImageUpload.vue.js (saveImage is the method to call)

import { bus } from “@/components/wizard/bus.js”;

not sure where to put this

bus.$on()

async saveImage() {

Now what i need is what do i emit? and how can i make it so saveImage is called when that button is pressed

Solution :

You emit the name of the event, which can be anything you want. For example: bus.$emit(‘upload-image’);, and then you listen to this event and trigger the callback with:

bus.$on(‘upload-image’, () => {
saveImage
.then(/* Do stuff */)
.catch(/* Do stuff */);
});`

For more information on how custom events work, you can refer to the documentation: https://vuejs.org/v2/guide/components-custom-events.html

[Vue.js] How to access Nuxt context variable from Vuex action

to access context variable to use the isMobile flag to select a different endpoint depending on the result. I could pass it on the dispatch from the component, but I know there should be one way to do it.

export const actions = {

signUpGoogle({ commit }) {
fireauth.useDeviceLanguage()

if (context.isMobile) {
fireauth.signInWithPopup(GoogleProvider).then …

} else {
fireauth.signInWithRedirect(GoogleProvider)
}

}

I saw here that it can be obtained on server init, but I really don’t wan’t to rely on this as caching will mess things up

https://nuxtjs.org/guide/vuex-store/#the-nuxtserverinit-action

Thanks for the help

Solution :

whenever you need to access Nuxt context where this pointer is not reachable to nuxt context use simply like below

window.$nuxt

hope it will serve the purpose

[Vue.js] Pass data from parent to child component in vue.js

when trying to pass data from a parent to a child component. However, the data when trying to pass keeps printing out as blank in the child component. My code:

In Profile.js (Parent component)

<template>

<div class=”container”>
<profile-form :user =”user”></profile-form>
</div>

</template>

<script>

import ProfileForm from ‘./ProfileForm’

module.exports = {

data: function () {
return {
user: ‘’
}
},

methods: {

getCurrentUser: function () {
var self = this
auth.getCurrentUser(function(person) {
self.user = person
})
},

}

</script>

In ProfileForm.js (Child component)

<template>

<div class=”container”>
<h1>Profile Form Component</h1>
</div>

</template>

<script>

module.exports = {

created: function () {
console.log(‘user data from parent component:’)
console.log(this.user) //prints out an empty string
},

}

</script>

Note - my user is loaded via my getCurrentUser() method… Can someone help?

Thanks in advance!

Solution :

To pass data via props, you have to declare them in child component:

module.exports = {
props: [‘user’],

created: function () {
console.log(‘user data from parent component:’)
console.log(this.user) //prints out an empty string
}
}

Solution 2:

Please note the following:

you missed out the line detailing ‘Vue.component’
you need to define the props passed in the child component
you need to call getCurrentUser() when the parent component initialises

Parent Component…

<template>

<div class=”container”>
<profile-form :user=”user”></profile-form>
</div>

</template>

<script>

import ProfileForm from ‘./ProfileForm’
Vue.component(‘profile-form’, ProfileForm);
export default {

data: function () {
return {
user: ‘’
}
},

methods: {
getCurrentUser: function () {
auth.getCurrentUser(function(person) {
this.user = person
})
},
created: function() {
this.getCurrentUser();
},
}

</script>

Child Component…

<template>

<div class=”container”>
<h1>Profile Form Component</h1>
</div>

</template>
<script>
export default {
props: [‘user’],
created: function () {
console.log(‘user data from parent component:’)
console.log(this.user) //prints out an empty string
},
}
</script>

[Vue.js] Vue-Multiselect - Deselecting group of pre-loaded values doesn't work

My code:

https://jsfiddle.net/bgarrison25/tndsmkq1/4/

Html:

<div id=”app”>
<label class=”typo__label”>Groups</label>
<multiselect
v-model=”value”
:options=”options”
:multiple=”true”
group-values=”libs”
group-label=”language”
:group-select=”true”
placeholder=”Type to search”
track-by=”name”
label=”name”>
<span slot=”noResult”>Oops! No elements found. Consider changing the search query.</span>
</multiselect>
<pre class=”language-json”><code>{ value }</code></pre>
</div>

Component:

new Vue({
components: {
Multiselect: window.VueMultiselect.default
},
data () {
return {
options: [
{
language: ‘Javascript’,
libs: [
{ name: ‘Vue.js’, category: ‘Front-end’ },
{ name: ‘Adonis’, category: ‘Backend’ }
]
},
{
language: ‘Ruby’,
libs: [
{ name: ‘Rails’, category: ‘Backend’ },
{ name: ‘Sinatra’, category: ‘Backend’ }
]
},
{
language: ‘Other’,
libs: [
{ name: ‘Laravel’, category: ‘Backend’ },
{ name: ‘Phoenix’, category: ‘Backend’ }
]
}
],
value: [
{ name: ‘Laravel’, category: ‘Backend’ },
{ name: ‘Phoenix’, category: ‘Backend’ }
]
}
}
}).$mount(‘#app’)

So there is created a multiselect using groups. If its a fresh load with no pre-selected options it works fine. However, if you have values pre-selected and try to deselect the group they are in it simply doesn’t work. Also, seems to be an issue if i deselect one manually and then select the group again.

Steps to reproduce in fiddle:

1) Laravel and Phoenix have been selected on load

2) click on the multiselect and choose “Other” to deselect the group. Nothing happens.

3) De-select “Phoenix” option and then click the “Other” group. Now you have “Laravel” / “Phoenix” / “Laravel” as options.

Wondering if when doing something wrong or if this is a bug. If its a bug I will simply post in their issues.

Solution :

the group deselect doesn’t work, because objects that you predefined in the this.value don’t refer to the objects in the this.options. They have the same structure and values, but they are different objects. To make the group deselect work with preselected values, set the value data property to [] by default, then add a mounted hook in which you preselect the “Other” group:

mounted() {
this.value = this.options.find(option => option.language === ‘Other’).libs;
}

With this, deselecting “Other” with preselected values works.

As for the other problem where duplicates can be selected, there is never used vue.js Multiselect, but the documentation describes events like @select or @input which you can probably use to filter out duplicates when needed. However, according to the docs, trackBy prop is used to compare the objects and it’s weird that it doesn’t work by itself.