I've created a vuex store like this in Nuxt.
export const state = () => ({
id: "",
type: null,
name: null,
});
export const mutations = {
setProfile(state, profile) {
state.id = profile.idStr;
state.type = profile.type;
state.name = profile.name;
}
};
export const getters = {
name(state) {
return state.name;
}
};
The data is stored with store.commit("profile/setProfile", profile.data); and successfuly set. (Values are shown in chrome dev-tools)
Now I'm trying to access the property name in one of my components using the mapGetters method like this.
import { mapGetters } from "vuex";
export default {
computed: mapGetters({
name: "profile/name"
})
};
My problem is that the getter is not found.
ERROR [vuex] unknown getter: profile/name
What is wrong with this approach?
Do you need to use mapGetters instead of mapState?
as of now (nuxt v2.14.7) the syntax is
export default {
computed: {
...mapGetters({getName: 'profile/name'}),
}
}
then in the component the getter can be used as
this.getName;
Related
I want to fetch some data from a firebase backend using an action to store it in vuex state. Currently I'm just working with some dummy data. Reading the data from the store in my index.vue works but as soon as I'm trying to get the action in index.vue I get the error that it is an unknown action type.
store/artikels.js
export const state = () => ({
artikel: [
{
id: "1",
titel: "Hallo",
untertitel: "Servas"
},
{
id: "2",
titel: "Was",
untertitel: "Wos"
},
{
id: "3",
titel: "Geht",
untertitel: "Wüst"
}
]
})
export const actions = () => ({
fetchArtikel() {
console.log('fetch data from firebase')
}
})
export const getters = () => ({
artikel: (state) => {
return state.artikel
}
})
this is index.vue
<script>
import { mapActions } from 'vuex'
export default {
name: 'App',
computed: {
artikel() {
return this.$store.state.artikels.artikel
}
},
async created() {
await this.$store.dispatch('artikels/fetchArtikel')
}
</script>
I've already tried to put the store in store/index.js without the namespace and also tried to dispatch it via mapActions and async fetch:
import mapActions from 'vuex'
methods: {
...mapActions(['artikels/fetchArtikels'])
}
or:
async fetch({store}) {
await store.dispatch('artikels/fetchArtikels')
}
So far, no luck. Can someone help me out? Thanks in advance!
The problem is your store's actions and getters are functions, but they need to be objects:
// store/artikels.js
export const actions = () => ({/*...*/}) // ❌ function
export const getters = () => ({/*...*/}) // ❌ function
export const actions = {/*...*/} // ✅ object
export const getters = {/*...*/} // ✅ object
demo
Working on a Vuejs application whereby I use Vuex for state management between the components.In Vuex store, I have an action that fetches some data from an API (which works fine) then populate it to the state (via a mutation). Next, I pass the updated state to the component using getters.
The problem is there is a problem populating data to the state from the action. In the DOM I have tried fetching via computed property or using the getter but get empty string
Vuex Store
const getDefaultState = () => {
return {
clientDeposit: ''
}
}
//state
const state = getDefaultState();
//getters
const getters = {
getDeposit: (state) => state.clientDeposit
}
//actions
const actions = {
fetchClients({ commit}) {
const clientId ="23"
axios.post('/api/motor/fetchClients', {
ClientId: clientId,
})
.then((response)=> {
//console.log(response); //returns data
const deposit = response.data;
commit('setIpfDeposit', deposit);
})
}
}
//mutations
const mutations = {
setIpfDeposit: (state, value) => (state.clientDeposit = value)
}
export default {
state,
getters,
actions,
mutations
}
Component
<template>
<div>
<button onclick="fetchClients()">Fetch Clients</button>
Deposit (Via computed property) : {{ fetchDeposit }}
Deposit (from getter) : {{ getDeposit }}
</div>
</template>
<script>
import { mapGetters , mapActions } from "vuex";
import axios from "axios";
export default {
name: "",
data() {
return {
}
},
computed: {
...mapGetters([
"getDeposit"
]),
fetchDeposit(){
return this.getDeposit
},
},
methods:{
...mapActions([
"fetchClients"
])
}
};
</script>
<style scoped>
</style>
You need to fetch the data first.
Import mapActions from vuex
import {mapActions, mapGetters} from 'vuex';
Bring in the fetchClients method in your component's methods object
methods:{
... mapActions(['fetchClients']),
}
Then in your component's created life cycle method call the fetchClients method
created(){
this.fetchClients();
}
I wrote the following code but it shows an error. What is the reason for this?
Error
[vuex] unknown action type: showRegisterLogin/show
HomePage.vue // component
When using the sh method This error is caused
import { mapState, mapActions } from "vuex";
export default {
name: "HomePage",
components: {
RegisterLogin
},
data() {
return {}
},
computed: {
...mapState({
showRegisterLogin: state => state.showRegisterLogin.show
}),
},
methods: {
sh() {
this.$store.dispatch('showRegisterLogin/show');
}
}
}
/ store / modules / showRegisterLogin.js
// States
const state = {
show: false,
};
// Getters
const getter = {
show (state) {
return state.show;
}
};
// Mutations
const mutation = {
showPage (state) {
return state.show = true;
},
hidePage (state) {
return state.show = false;
}
};
// Actions
const action = {
show({ commit }) {
commit('showPage');
},
hide({ commit }) {
commit('hidePage');
}
};
export default {
namespaced: true,
state,
getter,
mutation,
action
}
/ store / store.js
'use strict';
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
import showRegisterLogin from "./modules/showRegisterLogin";
export default new Vuex.Store({
modules: {
showRegisterLogin,
}
});
I also imported the store.js file into app.js and registered it in new vue
The structure of the store, module, and component are fine, except for the name of the store objects in your module:
getter should be getters
mutation should be mutations
action should be actions
Probably just typos. Those can't be arbitrarily named since Vuex looks specifically for those keys.
I'm trying to split up my Nuxt Vuex store files into separate files. And NOT have all Vuex getters, mutations and actions into one huge file. This demo project is on Github by the way.
I'v read this official Nuxt Vuex Store documentation; but can't seem to get it working. It's a bit vague on where to put stuff.
I have the following in these files:
Below is my: store/index.js
import Vue from "vue";
import Vuex from "vuex";
import Auth from "./modules/auth";
Vue.use(Vuex);
export const store = () => {
return new Vuex.Store({
state: {
},
modules: {
Auth
}
})
}
This is in my: store/auth.js
const state = () => {
username: null
};
const getters = {
username: state => {
return state.username;
},
isAuthenticated: state => {
return state.username != null;
}
};
const mutations = {
login: (vuexContext, username) => {
vuexContext.username = username;
this.$router.push("/dashboard");
},
logout: vuexContext => {
vuexContext.username = null;
this.$router.push("/");
}
};
const actions = {
};
export default {
state,
getters,
mutations,
actions,
};
And finally in my: pages/index.vue
This is where I'm calling that login mutation:
<script>
export default {
layout: "non-logged-in",
data() {
return {
username: null
}
},
methods: {
onSubmit() {
this.$store.commit("login", this.username);
}
}
}
</script>
The error I'm getting:
[vuex] unknown mutation type: login
What am I doing wrong here? I thought i'm importing all the stuff correctly in the store/index.js
You have to export your store constant like this inside your store/index.js file:
export default store
Put this code line at the end of your file.
So as #jeremy.raza described this is what I changed in order to get it working:
store/index.js
import Vue from "vue";
import Vuex from "vuex";
import Auth from "./modules/auth";
Vue.use(Vuex)
const store = () => {
return new Vuex.Store({
state: {
},
modules: {
Auth
}
})
}
export default store;
Changes in the store/auth.js
Note the changes in how I wrote the state, getters and mutations method notation.
const state = () => ({
username: null
});
const getters = {
username(state) {
return state.username;
},
isAuthenticated(state) {
return state.username != null;
}
};
const mutations = {
login(vuexContext, username) {
vuexContext.username = username;
this.$router.push("/dashboard");
},
logout(vuexContext) {
vuexContext.username = null;
this.$router.push("/");
}
};
const actions = {
};
export default {
state,
getters,
mutations,
actions,
};
i just wanna create dynamic registered module in vuex, but it seems doesnt work.
this is my store file
import Vuex from 'vuex'
import descriptionModule from './module/descriptionModule';
const {state: stateModule, getters, mutations} = descriptionModule;
const createStore = () => {
return new Vuex.Store({
state: {
descriptions: [],
},
mutations: {
addDescriptions(state, payload){
state.descriptions.push(state.descriptions.length + 1);
createStore().registerModule(`descriptionModule${payload}`, {
state: stateModule,
getters,
mutations,
namespaced: true // making our module reusable
});
}
}
})
};
export default createStore
and this is my custom module that i will registered
const state = () => {
return {description: ''}
};
const getters = {
description: (state) => state.description
};
const mutations = {
updateDescription(state, payloads){
state.description = payloads;
}
};
export default {
state,getters,mutations
}
and then this is my custom methods that will call addDescriptions mutation and commit updateDescription from registeredModule
beforeMount(){
console.log("hahahaha");
this.$store.commit('addDescriptions', this.id);
},
... more code ....
methods: {
onType(editor, content){
console.log(this.$store.state.a);
console.log(this.$store.state);
console.log(this.$store);
this.$store.commit(`descriptionModule${this.id}/updateDescription`, content, {root: true})
}
}
every onType called, i get an error unknown mutation type: descriptionModuleeditor1/updateDescription in browser.
currently iam following this solution link , but it doesnt work for me :(
can anyone solve this,,, sorry for bad english
invoke $store.registerModule() via component/pages on beforeMount():
beforeMount(){
this.$store.registerModule(`descriptionModule${this.id}`, {
state: stateModule,
getters,
mutations,
namespaced: true // making our module reusable
});
},