Reputation: 13
I have a problem about how to dispatch action in Vuex.
Now I'm making an app and using Vuex.
I want to dispatch vuex signin action in store/user.js from Login.vue,but it's not working.I want you to give me any tips.
Now it's the app's directory constructure.
enter image description here
index.js
import Vue from 'vue';
import Vuex from 'vuex';
import user from './modules/user'
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
user
}
})
export default store;
user.js
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios'
Vue.use(Vuex);
const user = new Vuex.Store({
state: {
current: null,
name: 'John'
},
mutations: {
setCurrent(state, payload) {
state.current = payload
}
},
actions: {
signin({commit}, {name, password}) {
axios.$post('http://localhost:3000/login', {name, password})
.then((response) => {
commit('setCurrent', response.data)
})
},
signout({commit}) {
commit('setCurrent', null)
}
}
})
export default user;
Login.vue
<template>
<v-container>
<v-card>
<v-card-title>
Login
</v-card-title>
<v-card-text>
<v-form>
<v-text-field
v-model="name"
:counter="10"
label="name"
required
></v-text-field>
<v-text-field
v-model="password"
:counter="10"
label="password"
required
></v-text-field>
<v-btn
class="mr-4"
@click="submitLoginDatas()"
>
Login
</v-btn>
</v-form>
</v-card-text>
</v-card>
{{ getName }}
<v-row class="button">
<v-col>
<v-btn
style="margin-top: 4px;"
to="/signup"
>
Signup
</v-btn>
</v-col>
</v-row>
</v-container>
</template>
<script>
export default {
data() {
return {
name: '',
password: ''
}
},
methods: {
async submitLoginDatas() {
console.log('HI')
console.log(this.$store.state.user.name)
// ここまでは呼ばれてる
// store自体も登録できている(下のgetNameから確認できる)
await this.$store.dispatch("signin",
{
name: this.name,
password: this.password
}
)
}
},
computed: {
getName() {
return this.$store.state.user.name
}
}
}
</script>
What I checked by now
・typo...ex.express actions as action like this
・namespace...now I don't express namespaced:true in user.js, but I tried namespaced: true in user.js with the below code. But it didn't work.
this.$store.dispatch("user/signin", {
name: this.name,
password: this.password
})
[vuex] unknown action type: signin
has been occuring and how to fix it.
Upvotes: 1
Views: 8934
Reputation: 14259
You are trying to use Vuex inside another Vuex - this is not going to work. Your Vuex module(s) should export a plain object instead of Vuex instance. Please change modules/user.js
to be
import axios from 'axios'
export default {
state(): {
return {
current: null,
name: 'John'
}
},
mutations: {
setCurrent(state, payload) {
state.current = payload
}
},
actions: {
signin({commit}, {name, password}) {
axios.$post('http://localhost:3000/login', {name, password})
.then((response) => {
commit('setCurrent', response.data)
})
},
signout({commit}) {
commit('setCurrent', null)
}
}
}
Upvotes: 1