I am new to feathers and vue js I don't understand this, when i log in a user the v-if directives works on the navbar, but when i refresh the page i notice that the user is no longer logged in still the JWT is stored in the localStorage.
App-Navbar.vue
<template>
<div>
<q-header bordered class="bg-white">
<q-toolbar>
<div class="q-gutter-sm" v-if="!user">
<q-btn to="/login" />
<q-btn to="/signup" />
</div>
<div class="q-gutter-sm" v-if="user">
<q-btn #click="logout"/>
</div>
</q-toolbar>
</q-header>
</div>
</template>
<script>
import { mapActions, mapState } from "vuex";
export default {
methods: {
...mapActions("auth", { authLogout: "logout" }),
logout() {
this.authLogout().then(() => this.$router.push("/login"));
}
},
computed: {
...mapState("auth", { user: "payload" })
}
};
</script>
You just need some logic to fetch your token on refresh.
You will first need to save it somewhere, let's say sessionStorage.
You can use vuex-persistedstate as you mentioned, but a lighter solution would be just setting your user property in the state of the store like this
user: sessionStorage.getItem(yourkey) ?? null
Related
Hi everyone and sorry for the title, I'm not really sure of how to describe my problem. If you have a better title feel free to edit !
A little bit of context
I'm working on a little personal project to help me learn headless & micro-services. So I have an API made with Node.js & Express that works pretty well. I then have my front project which is a simple one-page vue app that use vuex store.
On my single page I have several components and I want to add on each of them a possibility that when you're logged in as an Administrator you can click on every component to edit them.
I made it works well on static elements :
For example, here the plus button is shown as expected.
However, just bellow this one I have some components, that are loaded once the data are received. And in those components, I also have those buttons, but they're not shown. However, there's no data in this one except the title but that part is working very well, already tested and in production. It's just the "admin buttons" part that is not working as I expect it to be :
Sometimes when I edit some codes and the webpack watcher deal with my changes I have the result that appears :
And that's what I expect once the data are loaded.
There is something that I don't understand here and so I can't deal with the problem. Maybe a watch is missing or something ?
So and the code ?
First of all, we have a mixin for "Auth" that isn't implemented yet so for now it's just this :
Auth.js
export default {
computed: {
IsAdmin() {
return true;
}
},
}
Then we have a first component :
LCSkills.js
<template>
<div class="skills-container">
<h2 v-if="skills">{{ $t('skills') }}</h2>
<LCAdmin v-if="IsAdmin" :addModal="$refs.addModal" />
<LCModal ref="addModal"></LCModal>
<div class="skills" v-if="skills">
<LCSkillCategory
v-for="category in skills"
:key="category"
:category="category"
/>
</div>
</div>
</template>
<script>
import LCSkillCategory from './LCSkillCategory.vue';
import { mapState } from 'vuex';
import LCAdmin from '../LCAdmin.vue';
import LCModal from '../LCModal.vue';
import Auth from '../../mixins/Auth';
export default {
name: 'LCSkills',
components: {
LCSkillCategory,
LCAdmin,
LCModal,
},
computed: mapState({
skills: (state) => state.career.skills,
}),
mixins: [Auth],
};
</script>
<style scoped>
...
</style>
This component load each skills category with the LCSkillCategory component when the data is present in the store.
LCSkillCategory.js
<template>
<div class="skillsCategory">
<h2 v-if="category">{{ name }}</h2>
<LCAdmin
v-if="IsAdmin && category"
:editModal="$refs.editModal"
:deleteModal="$refs.deleteModal"
/>
<LCModal ref="editModal"></LCModal>
<LCModal ref="deleteModal"></LCModal>
<div v-if="category">
<LCSkill
v-for="skill in category.skills"
:key="skill"
:skill="skill"
/>
</div>
<LCAdmin v-if="IsAdmin" :addModal="$refs.addSkillModal" />
<LCModal ref="addSkillModal"></LCModal>
</div>
</template>
<script>
import LCSkill from './LCSkill.vue';
import { mapState } from 'vuex';
import LCAdmin from '../LCAdmin.vue';
import LCModal from '../LCModal.vue';
import Auth from '../../mixins/Auth';
export default {
name: 'LCSkillCategory',
components: { LCSkill, LCAdmin, LCModal },
props: ['category'],
mixins: [Auth],
computed: mapState({
name: function() {
return this.$store.getters['locale/getLocalizedValue']({
src: this.category,
attribute: 'name',
});
},
}),
};
</script>
<style scoped>
...
</style>
And so each category load a LCSkill component for each skill of this category.
<template>
<div class="skill-item">
<img :src="img(skill.icon.hash, 30, 30)" />
<p>{{ name }}</p>
<LCAdmin
v-if="IsAdmin"
:editModal="$refs.editModal"
:deleteModal="$refs.deleteModal"
/>
<LCModal ref="editModal"></LCModal>
<LCModal ref="deleteModal"></LCModal>
</div>
</template>
<script>
import LCImageRendering from '../../mixins/LCImageRendering';
import { mapState } from 'vuex';
import Auth from '../../mixins/Auth';
import LCAdmin from '../LCAdmin.vue';
import LCModal from '../LCModal.vue';
export default {
name: 'LCSkill',
mixins: [LCImageRendering, Auth],
props: ['skill'],
components: { LCAdmin, LCModal },
computed: mapState({
name: function() {
return this.$store.getters['locale/getLocalizedValue']({
src: this.skill,
attribute: 'name',
});
},
}),
};
</script>
<style scoped>
...
</style>
Then, the component with the button that is added everywhere :
LCAdmin.js
<template>
<div class="lc-admin">
<button v-if="addModal" #click="addModal.openModal()">
<i class="fas fa-plus"></i>
</button>
<button v-if="editModal" #click="editModal.openModal()">
<i class="fas fa-edit"></i>
</button>
<button v-if="deleteModal" #click="deleteModal.openModal()">
<i class="fas fa-trash"></i>
</button>
</div>
</template>
<script>
export default {
name: 'LCAdmin',
props: ['addModal', 'editModal', 'deleteModal'],
};
</script>
Again and I'm sorry it's not that I haven't look for a solution by myself, it's just that I don't know what to lookup for... And I'm also sorry for the very long post...
By the way, if you have some advice about how it is done and how I can improve it, feel free, Really. That how I can learn to do better !
EDIT :: ADDED The Store Code
Store Career Module
import { getCareer, getSkills } from '../../services/CareerService';
const state = () => {
// eslint-disable-next-line no-unused-labels
careerPath: [];
// eslint-disable-next-line no-unused-labels
skills: [];
};
const actions = {
async getCareerPath ({commit}) {
getCareer().then(response => {
commit('setCareerPath', response);
}).catch(err => console.log(err));
},
async getSkills ({commit}) {
getSkills().then(response => {
commit('setSkills', response);
}).catch(err => console.log(err));
}
};
const mutations = {
async setCareerPath(state, careerPath) {
state.careerPath = careerPath;
},
async setSkills(state, skills) {
state.skills = skills;
}
}
export default {
namespaced: true,
state,
actions,
mutations
}
Career Service
export async function getCareer() {
const response = await fetch('/api/career');
return await response.json();
}
export async function getSkills() {
const response = await fetch('/api/career/skill');
return await response.json();
}
Then App.vue, created() :
created() {
this.$store.dispatch('config/getConfigurations');
this.$store.dispatch('certs/getCerts');
this.$store.dispatch('career/getSkills');
this.$store.dispatch('projects/getProjects');
},
Clues
It seems that if I remove the v-if on the buttons of the LCAdmin, the button are shown as expected except that they all show even when I don't want them to. (If no modal are associated)
Which give me this result :
Problem is that refs are not reactive
$refs are only populated after the component has been rendered, and they are not reactive. It is only meant as an escape hatch for direct child manipulation - you should avoid accessing $refs from within templates or computed properties.
See simple demo below...
const vm = new Vue({
el: "#app",
components: {
MyComponent: {
props: ['modalRef'],
template: `
<div>
Hi!
<button v-if="modalRef">Click!</button>
</div>`
}
},
data() {
return {
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<my-component :modal-ref="$refs.modal"></my-component>
<div ref="modal">I'm modal placeholder</div>
</div>
The solution is to not pass $ref as prop at all. Pass simple true/false (which button to display). And on click event, $emit the event to the parent and pass the name of the ref as string...
I am facing a issue in my nuxt projct.
when i route the page by using nuxt-link, it doesn't render component in my page, i guess this is not making fetch call.
but when i use normal a href link, my page is working fine. everything is in place.
here is the link in a blog listing page component
// blog listing page snippet
<template>
<div>
<div v-for="blog in blogs.response.posts" :key="blog.id" class="col-md-3">
<nuxt-link :to="`/blogs/${blog.id}`" class="theme-blog-item-link"> Click to View Blog </nuxt-link>
</div>
</div>
</template>
<script>
export default {
data() {
return {
blogs: [],
}
},
async fetch() {
this.blogs = await fetch('https://www.happyvoyaging.com/api/blog/list?limit=4').then((res) => res.json())
},
}
</script>
but this works fine with if i replace nuxt-link with a href tag
<a :href="`/blogs/${blog.id}`" class="theme-blog-item-link">
Click to View Details
</a>
By click to that link, i want to view the detail of the blog by given id. that is _id.vue, code for that page is below.
//This is Specific Blog Details page code
<template>
<div class="theme-blog-post">
<div v-html="blogs.response.description" class="blogdesc"></div>
</div>
</template>
<script>
export default {
data(){
return {
blogs: []
}
},
async fetch() {
const blogid = this.$route.params.id
this.blogs = await fetch('https://www.happyvoyaging.com/api/blog/detail?id='+blogid+'').then((res) => res.json())
},
}
</script>
problem is on blogdetails page, where routing through nuxt-link not rendering the components but by normal a href link, it works fine
I am getting this error in console
vue.runtime.esm.js?2b0e:619 [Vue warn]: Unknown custom element: <PageNotFound> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
found in
---> <Error> at layouts/error.vue
<Nuxt>
<Layouts/default.vue> at layouts/default.vue
<Root>
Since your API requires some CORS configuration, here is a simple solution with the JSONplaceholder API of a index + details list collection.
test.vue, pretty much the blog listing in your case
<template>
<div>
<div v-if="$fetchState.pending">Fetching data...</div>
<div v-else>
<div v-for="item in items" :key="item.id">
<nuxt-link :to="`/details/${item.id}`"> View item #{{ item.id }}</nuxt-link>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
}
},
async fetch() {
const response = await fetch('https://jsonplaceholder.typicode.com/users')
this.items = await response.json()
},
}
</script>
details.vue, this one needs to be into a pages/details/_id.vue file to work
<template>
<div>
<button #click="$router.push('/test')">Go back to list</button>
<br />
<br />
<div v-if="$fetchState.pending">Fetching details...</div>
<div v-else>{{ details.email }}</div>
</div>
</template>
<script>
export default {
data() {
return {
details: {},
}
},
async fetch() {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${this.$route.params.id}`)
this.details = await response.json()
},
}
</script>
As you can see, I do only use async/await here and no then for consistency and clarity.
Try this example, then see for fixing the CORS issue. The latter is backend only and not anyhow related to Nuxt. A quick google search may give you plenty of results depending of your backend.
I am starting with vue.js, the code below is fine, the idea is when a person clicks in detail, I send it to another component to see the detail of the user this is fine, what I need is when the user clicks on it link back inside the detail component, keep the currentPage variable, what it does is set the currentPage variable to 1
I found something called keepAlive, but I really don't know how it works.
Also some way for mounted to run once.
this is my view here i call the Users component
<template>
<div>
<h1>Lista de Usuarios</h1>
<Users/>
</div>
</template>
<script>
import Users from "#/components/Users.vue";
export default {
name:"Usuarios",
components:{
Users
}
};
</script>
Users component
<template>
<div id="ejemplo">
<b-table
id="tabla"
:items="usuarios"
:per-page="perPage"
:current-page="currentPage"
:fields="fields"
small
>
<template v-slot:cell(Detalle)="fila">
<b-link :to="{ name: 'Usuario', params: { id:fila.item.id} }">Ver Más</b-link>
</template>
<template v-slot:cell(Elimina)="fila">
<b-button size="sm" #click="elimina(fila.item.id)" class="mr-2">
Elimina</b-button >
</template>
</b-table>
<b-pagination
v-model="currentPage"
:total-rows="total"
:per-page="perPage"
aria-controls="tabla"
></b-pagination>
</div>
</template>
<script>
export default {
name:"Users",
data(){
return{
perPage: 3,
currentPage: 1,
usuarios:[],
fields: ['id', 'name', 'Detalle','Elimina'],
total:0,
}
},
methods:{
async Listar(){
let response = await fetch('https://jsonplaceholder.typicode.com/users')
let data= await response.json()
this.usuarios= await data
this.total= await this.rows()
},
rows() {
return this.usuarios.length
},
elimina(id){
this.usuarios=this.usuarios.filter(usuario=>usuario.id !== id)
}
},
mounted(){
this.Listar()
}
}
</script>
Maybe in your case it makes sense to use Vuex. Vuex is something like a a globally store for your Vue-Application. You could set the "currentPage"-Variable in there and change it's value by using "mutations".
I have a layout theme/default which has vue-router inside like this
<template>
<div id="app">
<component :is = "layout">
<router-view></router-view>
</component>
</div>
</template>
<script>
const default_layout = "theme";
export default {
computed: {
layout(){
return ( this.$route.meta.layout || default_layout) + '-layout';
}
},
};
</script>
And then the theme layout is like this:
<template>
<div class="app-home">
<nav-bar/>
<div class="container-fluid section">
<div class="left-fixed">
<side-bar/>
</div>
<div class="right-card">
<slot />
</div>
</div>
</div>
</template>
<script>
import NavBar from './Navbar'
import SideBar from './Sidebar'
export default {
data() {
return {
}
},
mounted(){
},
components: {
NavBar,
SideBar
}
}
</script>
Now I have to pass current auth user in Navbar and Sidebar for logout and current user role which can be obtained from vue-auth $auth but only inside router component. Can anybody help it to fix this.
Using vuex I had made a state which I call as computed property and I set whenever User logged in.
My App.vue contains below content:
<template>
<v-app>
<core-toolbar />
<core-drawer />
<core-view />
</v-app>
</template>
But I want to hide <core-toolbar /> and <core-drawer /> when it is routed to login page. I am planning to use v-if to hide them. But how can I check whether the current route is login?
Yes - If you used vue-router, you can use the $route object to verify current URL.
You can log the route object and verify.
I add name to routes so
computed: {
isLogin() {
return this.$route.name === 'Login'
}
}
and
<template>
<v-app>
<core-toolbar v-if="isLogin"/>
<core-drawer v-if="isLogin"/>
<core-view />
</v-app>
</template>
You can get many more values like queries / params -
Read more here Vue Router
You can use $route.name
<core-toolbar v-show="$route.name!=='login'" />
<core-drawer v-show="$route.name!=='login'" />
You can access your route data from your Vue instance
<template>
<v-app>
<core-toolbar />
<core-drawer v-if="!isLogin" />
<core-view v-if="!isLogin"/>
</v-app>
</template>
<script>
export default {
computed: {
isLogin() {
return this.$route.name == 'login'
}
}
}
</script>
Inspect the object this.$route to get the right params you need.
You can name the routes with an id:
const routes = [
{
path: '/login',
name: 'login’,
component: 'login'
},
];
Then you can access this.$route whenever to get information about the current route, even in v-if:
<template>
<v-app>
<core-toolbar v-if="$route.name != 'login'" />
<core-drawer v-if="$route.name != 'login'" />
<core-view />
</v-app>
</template>
you can use javascript to get the path
isLoginPage(){
var path = window.location.pathname.split('/')[1]
if(path == 'login'){
return true
}
return false
}
For future reference in Vue3 you need to do the following
import { useRoute } from "vue-router";
import {computed} from "vue";
Then:
const router= userRouter()
const isLogin= computed(()=>router.name==="Login")