Show authenticated user in vuejs - laravel

I've tried to follow the following tutorial in laravel 5.3 and vue 2.0:
https://www.youtube.com/watch?v=CeXDx4hdT1s
Products.vue:
<my-product :key="product.id"
v-for="product in products"
:authenticatedUser="authenticatedUser"
:product="product">
...
computed: {
authenticatedUser() {
this.$auth.getAuthenticatedUser()
}
},
Product.vue:
export default{
props: ['product', 'authenticatedUser']
}
Auth.js
setAuthenticatedUser(data){
authenticatedUser = data;
},
getAuthenticatedUser(){
return authenticatedUser;
}
Navbar.vue:
export default {
data() {
return {
isAuth: null
}
},
created() {
this.isAuth = this.$auth.isAuthenticated();
this.setAuthenticatedUser();
},
methods: {
setAuthenticatedUser() {
this.$http.get('api/user')
.then(response => {
this.$auth.setAuthenticatedUser(response.body);
console.log(this.$auth.getAuthenticatedUser());
})
}
}
I try to pass the authenticated user which is called in the Products.vue within the Product.vue
For that, at each login, the setAuthenticated method in the Navbar.vue is called where the authenticated user should be set in the corresponding method.
But when I check the property in the debugger of the browser, it's written Props authenticatedUser: undefinded. In fact the authenticated user is not shown.
Any ideas what it's missing?

In computed you need to return the value you want the property to take.
It should be:
computed: {
authenticatedUser() {
return this.$auth.getAuthenticatedUser()
}
},

Related

Cannot access state by getters vuex vuejs

I am new to vuex I want to access user object that is inside in state by the getters getUser() method, I tried to call this
console.log(this.$store.getters.getUser); in mounted method but no results.
I tried to console log inside mutations and it return the user object.
I also followed documentations and googled the solutions but nothing happen
What else am I missing?
store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
user: {},
},
getters: {
getUser: state => {
return state.user
}
},
mutations: {
auth_user(state,data) {
state.user = data
}
},
actions: {
fetchAuthUser(context){
axios.get('/user-data').then(response => {
context.commit("auth_user",response.data)
}).catch({});
}
},
})
export default store
Index.js
mounted(){
// this.auth_user;
this.getCategories();
this.$store.dispatch('fetchAuthUser', this.auth_user);
console.log(this.$store.getters.getUser);
},
Your action is async and should return a promise.
fetchAuthUser(context){
return axios.get('/user-data').then(response => {
context.commit("auth_user",response.data)
}).catch({});
}
In your mounted you can use then to handle data.
mounted(){
// this.auth_user;
this.getCategories();
this.$store.dispatch('fetchAuthUser', this.auth_user).then(() => {
console.log(this.$store.getters.getUser);
});
}

Is it possible to show the computed/Methods calculated values from one component to another component in Vue Js?

Parent Component
<template>
<ChildComponent #send-message="handleSendMessage" />
</template>
Parent Component Script
export default {
methods: {
handleSendMessage(event, value) {
console.log('From the child:', value);
}
}
}
child Component
export default {
props: {
method: { type: Function },
},
computed:{
rep_9100_3() {
return parseInt(this.rep_6000_3) - this.decutable_allowance
},
},
mounted() {
this.$emit('send-message', this.rep_9100_3);
}
}
Yes you simply need to change handleSendMessage(event, value) to handleSendMessage(value).
One extra thing to note. It's could practice to pass a radix value when using parseInt:
parseInt(this.rep_6000_3, 10)

How to get data by axios call in a mounted component?

I'm working on getting data from API by performing api call with axios. But my attempts to get data from api aren't succesful. How to make it work?
export default {
mounted() {
this.fetchData()
},
data() {
return {
users:[]
}
},
methods: {
fetchData(){
axios.get('api/person')
.then(response => (this.users= response.data))
.catch(error => console.log(error));
}
},
}
In ExampleComponent have these lines
<template>
...
<div>{{users.name}}</div>
<div>{{users.ip}}</div>
...
</template>
In api.php
Route::get('/person', function() {
$users = DB::table('user_info')->select('ip','name')->get();
return $users;
});
Running php artisan tinker I did
DB::table('user_info')->select('ip','name')->get();
I've got all my data from DB(users with names and IP's).
In the dev console, I see my data in response tab. But it is nothing in my page.
you need v-for:
<div v-for="user in users">
<div>{{user.name}}</div>
<div>{{user.ip}}</div>
</div>
so for every users you will show info.
There is a problem in vue : it should be {users.ip} and {users.name} in template.
that is how i get my data.
<script>
export default {
data() {
return {
properties: []
}
},
methods: {
loadproperty(){
axios.get('allhouses').then(response => this.properties = response.data);
},
},
mounted() {
this.loadproperty();
}
}
</script>

promisse value undefined axios

I'm trying to get values using axios and on my browser returns [[PromisseValue]] undefined. Follow my code. Please, help-me... thanks
This is my data to get
<script>
export default {
props: ['endpoint'],
data () {
return {
response: {
table: '',
displayable: [],
records: []
}
}
},
methods: {
getRecords () {
return axios.get(`${this.endpoint}`).then((response) => {
console.log(response.data.data.table)
})
}
},
mounted () {
this.getRecords()
}
}
It will return promise because AXIOS is a promise function that you are trying to return.
axios.get(`${this.endpoint}`).then((response) => {
this.response.table = response.data.data.table
})
after axios call you need save it into your state or data the response then use it wherever you want.

How to make the delay when a user check on Vue.js?

I have SPA application on Vue.js + Laravel. Authorization logic, completely delegated to Laravel app. However, i need check auth status, when routing has changed. I create small class, which responsible for it.
export default {
user: {
authenticated : false
},
check: function(context) {
context.$http.get('/api/v1/user').then((response) => {
if (response.body.user != null) {
this.user.authenticated = true
}
}, (response) =>{
console.log(response)
});
}
Within the component has a method that is called when a change url.
beforeRouteEnter (to, from, next) {
next(vm =>{
Auth.check(vm);
if (!Auth.user.authenticated) {
next({path:'/login'});
}
})
}
Function next() given Vue app instance, then check user object. If user false, next() call again for redirect to login page. All it works, but only when the page is already loaded. If i'll reload /account page, there is a redirect to /login page, because request to Api not completed yet, but code will continue execute. Any idea?
Quite simple to do, you need to make your code work asynchronously and hold routing before request is completed.
export default {
user: {
authenticated : false
},
check: function(context) {
return context.$http.get('/api/v1/user').then((response) => {
if (response.body.user != null) {
this.user.authenticated = true
}
}, (response) => {
console.log(response)
});
}
}
then
beforeRouteEnter (to, from, next) {
next(vm => {
Auth.check(vm).then(() => {
if (!Auth.user.authenticated) {
next({path:'/login'});
} else {
next()
}
}
})
}
Other pro tips
Display some loading indicator when loading so your application doesn't seem to freeze (you can use global router hooks for that)
If you are using vue-resource, consider using interceptors (perhaps in addition to the routing checks)
Consider using router.beforeEach so that you don't have to copy-paste beforeRouteEnter to every component
Done. Need to return promise like that
check: function(context) {
return context.$http.get('/api/v1/user').then((response) => {
if (response.body.user != null) {
this.user.authenticated = true
}
}, (response) =>{
console.log(response)
});
}
and then
beforeRouteEnter (to, from, next) {
Auth.check().then(()=>{
if(!Auth.user.authenticated)
next({path:'/login'})
else
next();
})
}

Resources