Vuex State data is not persisting? - vue.js

I'm working on admin panel in vuejs and using vuex for state management.
store/module/home/home.js:
import instance from "../../../services/Http";
const state = {
usersCount: 0,
customersCount: 0,
chefsCount: 0,
driversCount: 0,
Users: [],
};
const getters = {
Userscount: state => state.usersCount,
Customerscount: state => state.customersCount,
Chefscount: state => state.chefsCount,
Driverscount: state => state.driversCount,
users: state => state.Users,
};
const actions = {
getStats({commit})
{
instance.get('admin/stats').then(res => commit('setStats', res.data));
},
getUsers({commit})
{
instance.get('admin/users').then(res => commit('setUsers', res.data));
}
};
const mutations = {
setStats:(state, data) => {
state.usersCount = data.usersCount;
state.customersCount = data.customersCount;
state.chefsCount = data.chefsCount;
state.driversCount = data.driversCount;
},
setUsers:(state, data) => { state.Users = data.users}
};
export default {
state,
getters,
actions,
mutations
}
and then i'm calling getStats and getUsers actions in two different components in created method of respective components.
The issue is that getStats and setStats is executed but it does not set the data, but getUsers and setUsers is working as expected.
src/components/layouts/Widgets.vue:
<template>
<!-- Widgets -->
<div class="row">
<div class="col-lg-3 col-md-6">
<div class="card">
<div class="card-body">
<div class="stat-widget-five">
<div class="stat-icon dib flat-color-1">
<!-- <i class="pe-7s-cash"></i>-->
<i class="pe-7s-users"></i>
</div>
<div class="stat-content">
<div class="text-left dib">
<div class="stat-text"><span class="count">{{ Userscount }}</span></div>
<div class="stat-heading">Total Users</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="card">
<div class="card-body">
<div class="stat-widget-five">
<div class="stat-icon dib flat-color-2">
<!-- <i class="pe-7s-cart"></i>-->
<i class="pe-7s-users"></i>
</div>
<div class="stat-content">
<div class="text-left dib">
<div class="stat-text"><span class="count">{{ Chefscount }}</span></div>
<div class="stat-heading">Total Chefs</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="card">
<div class="card-body">
<div class="stat-widget-five">
<div class="stat-icon dib flat-color-8">
<!-- <i class="pe-7s-browser"></i>-->
<i class="pe-7s-users"></i>
</div>
<div class="stat-content">
<div class="text-left dib">
<div class="stat-text"><span class="count">{{ Customerscount }}</span></div>
<div class="stat-heading">Total Customers</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="card">
<div class="card-body">
<div class="stat-widget-five">
<div class="stat-icon dib flat-color-4">
<i class="pe-7s-users"></i>
</div>
<div class="stat-content">
<div class="text-left dib">
<div class="stat-text"><span class="count">{{ Driverscount }}</span></div>
<div class="stat-heading">Total Drivers</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /Widgets -->
</template>
<script>
import {mapActions,mapGetters} from 'vuex';
export default {
name: "Widgets",
created() {
this.getStats();
},
computed: mapGetters(['Userscount','Customerscount','Chefscount','Driverscount']),
methods:{
...mapActions(['getStats'])
},
}
</script>
i'have also attached images showing of vue js dev tools for vuex that data is stored in state but it is not being displayed.
edit-1:
setStats-after console.log
{usersCount: 12, customersCount: 4, chefsCount: 7, driversCount: 0, postsCount: 22}chefsCount: 7customersCount: 4driversCount: 0postsCount: 22usersCount: 12__proto__: Object
Edit-2:
vuex binding widgets components
Edit-3:
Store/index.js:
import Vue from 'vue'
import Vuex from 'vuex'
import auth from "./modules/auth/auth";
import home from "./modules/home/home";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
auth,
home
}
});
sr/main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false;
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!store.getters.isLoggedIn)
{
next({
name: 'login',
})
}
else
{
next();
}
}
else if(to.matched.some(record => record.meta.Visitor)) {
if (store.getters.isLoggedIn)
{
next({
name: 'home',
})
}
else
{
next();
}
}
else
{
next()
}
});
new Vue({
store,
router,
render: h => h(App)
}).$mount('#app');
src/components/layout/Main.vue:
<template>
<div class="Main">
<SideBar/>
<div id="right-panel" class="right-panel">
<Header/>
<!-- Content -->
<div class="content">
<div class="animated fadeIn">
<Widgets/>
<div class="clearfix"></div>
<Users/>
<div class="clearfix"></div>
<Footer/>
</div>
</div>
</template>
<script>
import SideBar from "./SideBar";
import Header from "./Header";
import Footer from "./Footer";
import Widgets from "./Widgets";
import Users from "../users/Users";
export default {
name: "Main",
components: {Users, Widgets, Footer, Header, SideBar}
}
</script>
<style scoped>
#weatherWidget .currentDesc {
color: #ffffff!important;
}
.traffic-chart {
min-height: 335px;
}
#flotPie1 {
height: 150px;
}
#flotPie1 td {
padding:3px;
}
#flotPie1 table {
top: 20px!important;
right: -10px!important;
}
.chart-container {
display: table;
min-width: 270px ;
text-align: left;
padding-top: 10px;
padding-bottom: 10px;
}
#flotLine5 {
height: 105px;
}
#flotBarChart {
height: 150px;
}
#cellPaiChart{
height: 160px;
}
</style>
Any help will be appreciated.
Thanks.

you forgot to add "..." before the 'mapGetters', "...mapGetters"

I think your problem would be solved by implementing the strict-mode in Vuex, by the way, it's turned off by default.
take a look here: https://vuex.vuejs.org/guide/strict.html

Have you tried using mapState instead of mapGetters? As your values are just being updated, but your getters aren't computed values, they just map to your state.
Instead of:
<script>
import {mapActions,mapGetters} from 'vuex';
export default {
name: "Widgets",
created() {
this.getStats();
},
computed: mapGetters(['Userscount','Customerscount','Chefscount','Driverscount']),
methods:{
...mapActions(['getStats'])
},
}
</script>
Maybe try:
<script>
import {mapActions,mapGetters} from 'vuex';
export default {
name: "Widgets",
created() {
this.getStats();
},
computed: mapState({
Userscount: state => state.home.Userscount,
Customerscount: state => state.home.Customerscount,
Chefscount: state => state.home.Chefscount,
Driverscount: state => state.home.Drivers.count
}),
methods:{
...mapActions(['getStats'])
},
}
</script>

Related

Vue don't give #click to a single element when using v-for to create them

I'm trying to make every single element created with the v-for the ability to toggle between 'face' class, but it happens that it toggles everything created with the v-for.
<div class="deckPairs">
<div class="deckBoxOne" v-for="base in cards" :key="base.id" >
<div class="deckBoxBlanc" :class="{face : face}" #click="face = !face">
<img class="deckPairsImage" style="z-index: 3" alt="Vue logo" :src="require('../assets/rightCardSide.png')">
</div>
<div class="deckBoxImg" :class="{face : !face}" #click="face = !face">
<img class="deckPairsImages" style="z-index: 2" :src="require(`../assets/images/${base.url}`)">
</div>
</div>
</div>
Script:
export default {
setup() {
const face = ref(false)
return { face }
},
data(){
return {
face: false,
}
},
methods: {
}
}
Create a component to encapsulate the v-for content.
// new-component.vue
<template>
<div>
<div class="deckBoxBlanc" :class="{face : face}" #click="face = !face">
<img class="deckPairsImage" style="z-index: 3" alt="Vue logo" :src="require('../assets/rightCardSide.png')">
</div>
<div class="deckBoxImg" :class="{face : !face}" #click="face = !face">
<img class="deckPairsImages" style="z-index: 2" :src="require(`../assets/images/${base.url}`)">
</div>
</div>
</template>
export default {
data(){
return {
face: false
}
}
}
Now update v-for to use the new component.
<div class="deckPairs">
<div class="deckBoxOne" v-for="base in cards" >
<new-component :key="base.id"/>
</div>
</div>
You can use base.id instead boolean and v-show directive:
const { ref } = Vue
const app = Vue.createApp({
el: "#demo",
setup() {
const face = ref(false)
const cards = ref([{id: 1, url: "https://picsum.photos/100"}, {id: 2, url: "https://picsum.photos/101"}, {id: 3, url: "https://picsum.photos/102"}])
const rightCardSide = ref("https://picsum.photos/103")
const setFace = (val) => {
face.value = val
}
return { cards, face, rightCardSide, setFace }
},
})
app.mount('#demo')
.deckPairs {
display: flex;
}
.deckBoxOne {
cursor: pointer;
}
<script src="https://unpkg.com/vue#3/dist/vue.global.prod.js"></script>
<div id="demo">
<div class="deckPairs">
<div class="deckBoxOne" v-for="base in cards" :key="base.id" >
<div class="deckBoxBlanc" v-show=" face !== base.id" #click="setFace(base.id)">
<img class="deckPairsImage" alt="Vue logo" :src="rightCardSide">
</div>
<div class="deckBoxImg" v-show="face === base.id" #click="setFace(false)">
<img class="deckPairsImages" :src="base.url">
</div>
</div>
</div>
</div>

Vuejs 3 props are Proxy

I am passing array as a prop to another component, and when I want to read this on mounted in that component, I got Proxy {}. How to read data from this prop? You can see in example when I want to console log prop, result is Proxy {}. I can see all values in HTML structure, but not in the console on mounted.
<template>
<div class="custom-select-container">
<div class="selected-item" #click="openSelect">
<span class="selected-items-text">{{ selectedItem.name }}</span>
<span class="icon-arrow1_b selected-items-icon" :class="{ active: showOptions }" />
</div>
<transition name="fade">
<ul v-show="options.length && showOptions" class="custom-select-options">
<li v-for="(option, index) in options" :key="index" class="custom-select-item">{{ option.name }}</li>
</ul>
</transition>
</div>
</template>
<script>
import { ref, onMounted } from 'vue'
export default {
props: {
options: {
type: Array,
default: () => []
}
},
setup(props) {
let showOptions = ref(false);
let selectedItem = ref(props.options[0])
const openSelect = () => {
showOptions.value = !showOptions.value
}
onMounted(() => {
console.log('test', props.options)
})
return {
openSelect,
showOptions,
selectedItem
}
}
}
</script>
Parent component where I am passing data:
<template>
<div class="page-container">
<div>
<div class="items-title">
<h3>List of categories</h3>
<span>({{ allCategories.length }})</span>
</div>
<div class="items-container">
<div class="item" v-for="(category, index) in allCategories" :key="index">
<span class="item-cell size-xs">{{ index + 1 }}.</span>
<span class="item-cell size-l">{{ category.name }}</span>
</div>
</div>
</div>
<custom-select
:options="allCategories"
/>
</div>
</template>
<script>
import CustomSelect from '../components/Input/CustomSelect'
import { computed } from 'vue'
import { useStore } from 'vuex'
export default {
components: {
CustomSelect
},
computed: {
},
setup() {
const store = useStore()
const allCategories = computed(() => store.getters['categories/getAllCategories'])
return {
allCategories
}
}
}
</script>
That's how reactivity works in Vue3.
use
console.log(JSON.parse(JSON.stringify(data))
or
console.log(JSON.stringify(data, null, 2))
to show the content of proxies in console

Error When clicking 'Print' button using 'Vue HTML to Paper'

I have a vue app and I'm trying to implement the 'Vue HTML to Paper'.
I have followed all the instructions on https://randomcodetips.com/vue-html-to-paper/ but when i click my 'Print' button I get the following error.
Main.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './App.vue';
import { routes } from './routes';
import { store } from './store/store';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap-vue/dist/bootstrap-vue.css';
import VueHtmlToPaper from 'vue-html-to-paper';
const router = new VueRouter({
// Loads page always at the top
scrollBehavior() {
$('.tooltip, .popover').tooltip('hide');
return { x: 0, y: 0 };
},
routes,
});
const options = {
name: '_blank',
specs: [
'fullscreen=yes',
'titlebar=yes',
'scrollbars=yes'
],
styles: [
'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css',
'https://unpkg.com/kidlat-css/css/kidlat.css'
]
}
Vue.use(VueRouter, VueHtmlToPaper, options);
...
Component
<template>
<div>
<loader v-if="loading" />
<div v-else class="form-group row d-flex justify-content-center">
<div class="col-10">
<div id="printMe" class="card">
<div class="card-header">
<div class="row d-flex align-items-center">
<div class="col">
Order details for: <span class="text-info">{{ 'PACK' + productOrder.id }}</span>
</div>
<div class="col d-flex justify-content-end">
<button class="btn btn-info" #click="print">Print</button>
......
<script>
export default {
data() {
return {
...
output: null
....
methods: {
print () {
// Pass the element id here
this.$htmlToPaper('printMe');
},
...
You can't register multiple plugins in one Vue.use.
Try replacing the line
Vue.use(VueRouter, VueHtmlToPaper, options);
With
Vue.use(VueRouter);
Vue.use(VueHtmlToPaper, options)

app.js:81010 [Vue warn]: Error in mounted hook: "ReferenceError: $store is not defined"

I am attempting to refactor my code to use vuex. I am getting 2 errors: app.js:81010 [Vue warn]: Error in mounted hook: "ReferenceError: $store is not defined" and ReferenceError: $store is not defined. I think I imported vuex properly.
My goal is to update my bootstrap-vue data-table with the employee data from my database using vuex.
In the EmployeeDataTable.vue file I have a getEmployees method in methods: {} which I would like it to dispatch the fetchAllEmployees action from employees.js. fetchAllEmployees should grab all of the employees from the database and save the result to the employees.js employees: [] state.
I am now confused and need help getting in the right direction to fix this issue.
I don't know if I needed to show all of this code, but I wanted to show the flow of my components.
Entry point App.js:
import Vue from 'vue';
import store from './store';
import router from './router';
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue'
import App from './components/App';
Vue.use(BootstrapVue);
Vue.use(IconsPlugin);
require('./bootstrap');
const app = new Vue({
el: '#app',
components: {
App,
},
router,
store,
});
Vuex Store index.js:
import Vue from 'vue';
import Vuex from 'vuex';
import Employees from './modules/employees';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
Employees,
}
});
Vuex module employees.js:
const state = {
employees: [],
employeesStatus: null,
};
const getters = {
allEmployees: (state) => state.employees
};
const actions = {
fetchAllEmployees({commit, state}) {
commit('setPostsStatus', 'loading');
axios.get('/api/employees')
.then(res => {
commit('employees', res.data);
commit('employeesStatus', 'success');
})
.catch(error => {
commit('setEmployeesStatus', 'error');
});
},
};
const mutations = {
setEmployees(state, employees) {
state.employees = employees;
},
setEmployeesStatus(state, status) {
state.employeesStatus = status;
}
};
export default {
state, getters, actions, mutations,
};
App.vue:
<template>
<div>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "App"
}
</script>
<style scoped>
</style>
DashBoard.vue:
<template>
<div>
<b-container>
<b-row>
<b-col class="col-12 col-sm-12 col-md-5 col-lg-4 col-xl-4">
<b-list-group class="d-flex horiz mx-5">
<b-list-group-item class="list-group-item-padding">
<b-link v-on:click="component='home'">
<i class="fas fa-home"></i>
<span class="custom-sm-d-none">Home</span>
</b-link>
</b-list-group-item>
<b-list-group-item class="list-group-item-padding">
<b-link v-on:click="component = 'projects'">
<i class="fas fa-project-diagram"></i>
<span class="custom-sm-d-none">Projects</span>
</b-link>
</b-list-group-item>
<b-list-group-item class="list-group-item-padding">
<b-link v-on:click="component = 'employees'">
<i class="fas fa-user"></i>
<span class="custom-sm-d-none">Employees</span>
</b-link>
</b-list-group-item>
<b-list-group-item class="list-group-item-padding">
<b-link v-on:click="component = 'customers'">
<i class="fas fa-users"></i>
<span class="custom-sm-d-none">Customers</span>
</b-link>
</b-list-group-item>
<b-list-group-item class="list-group-item-padding">
<b-link v-on:click="component = 'batch-create-material-list'">
<i class="fas fa-toolbox"></i>
<span class="custom-sm-d-none">Materials</span>
</b-link>
</b-list-group-item>
<b-list-group-item class="">
<b-link v-on:click="component = 'product-list'">
<i class="fas fa-clipboard-list icon-5x"></i>
<span class="custom-sm-d-none">Tasks</span>
</b-link>
</b-list-group-item>
</b-list-group>
</b-col>
<b-col class="col-12 col-md-7 col-lg-8 col-xl-8">
<keep-alive>
<component v-bind:is="component"></component>
</keep-alive>
</b-col>
</b-row>
</b-container>
</div>
</template>
<script>
import Home from '../../components/admin/Home';
import Projects from '../../components/admin/Projects';
import Employees from '../../components/admin/Employees';
import Customers from '../../components/admin/Customers'
import ProductList from '../../components/admin/ProductList';
import CreateProductAndCategory from '../../components/admin/CreateProductAndCategory';
export default {
name: 'Dashboard',
components: {
'home': Home,
'projects': Projects,
'employees': Employees,
'customers': Customers,
'product-list': ProductList,
'batch-create-material-list': CreateProductAndCategory,
},
data() {
return {
component: 'product-list',
}
},
}
</script>
<style scoped>
/* small screen below 768px width */
#media only screen and (max-width : 691px) {
.custom-sm-d-none{display:none;}
.horiz {
flex-direction: row;
justify-content: space-evenly;
padding-bottom: 10px;
}
.list-group-item-padding {
margin-right: 10px;
}
}
</style>
Component Employees.vue:
<template>
<div>
<EmployeeDataTable/>
<CreateEmployee />
</div>
</template>
<script>
import EmployeeDataTable from "./EmployeeDataTable"
import CreateEmployee from "./CreateEmployee"
export default {
components: {
EmployeeDataTable,
CreateEmployee,
},
}
</script>
<style scoped>
</style>
Component EmployeeDataTable.vue:
<template>
<div class="overflow-auto pb-3" style="background: white; ">
<b-card
header="Employees"
header-tag="header"
>
<b-pagination
v-model="currentPage"
:total-rows="rows"
:per-page="perPage"
aria-controls="my-table"
></b-pagination>
<p class="mt-3">Current Page: {{ currentPage }}</p>
<b-table
id="employee-table"
ref="employee-table"
:items="items"
:per-page="perPage"
:current-page="currentPage"
small
></b-table>
</b-card>
</div>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
name: "EmployeeDataTable",
data() {
return {
perPage: 3,
currentPage: 1,
items: [],
}
},
computed: {
...mapGetters(['allEmployees']),
rows() {
return this.items.length
}
},
methods: {
getEmployees() {
$store.dispatch('fetchAllEmployees').then(() => {
console.log('Dispatched getEmployees method!');
});
}
},
mounted() {
this.getEmployees();
}
}
</script>
Use this.$store instead of $store in the component. Change your API call to:
axios.get('/api/employees')
.then(res => {
commit('setEmployees', res.data);
commit('setEmployeesStatus', 'success');
})
.catch(error => {
commit('setEmployeesStatus', 'error');
});
The difference now is that you're calling the mutation names. In your success commit, you had the state names instead of the mutations.
One common convention people use in Vuex is to name mutations in all caps, and it might help in a situation like this (by making it more obvious if you used a state name instead). You'd rename them to SET_EMPLOYEES and SET_EMPLOYEES_STATUS.

Vue Eventbus: handler.apply is not a function

I want to reload one of my components when an other component changes (for example I send a put with axios)
I tried it with eventbus but I got this error:
handler.apply is not a function
In the component where I want to trigger:
EventBus.$emit('compose-reload', Math.random()*100);
Where I want to be triggered:
<template>
<div class="">
<div class="">
<div class="columns">
<div class="column is-one-fifth">
<div class="box">
<Menu></Menu>
</div>
</div>
<div class="column is-four-fifth">
<div class="box">
<router-view :key="key"></router-view>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import Menu from './includes/Menu'
import EventBus from '../../../event-bus';
export default {
components: {
Menu,
},
data() {
return {
key: null
}
},
mounted(){
EventBus.$on('compose-reload', this.key);
},
created(){
this.key = Math.random()*100
}
}
</script>
EventBus.$on expects a handler function as a second argument but the variable this.key is passed in, hence the error.
You should change this :
mounted(){
EventBus.$on('compose-reload', this.key);
}
To this :
mounted(){
EventBus.$on('compose-reload', key => {
this.key = key;
});
}