## 初めに
現在Vue.jsを学習しており備忘録として、Vuexの使用方法を残していきます。
state
stateは格納したいデータを記述する
const state = {
user: null
}
mutation
stateを更新するメソッドを定義する。
stateの第一引数はstate, 第二引数はデータ。
const mutations = {
setUser(state, user) {
state.user = user;
}
}
action
- actionにて非同期処理にてバックエンド側のconectionを行いデータのやりとりをおこう。受け取ったデータはcontextを使用しmututationをよびstateの更新を行う。
- front側からの通信はthis.$store.dispatch('modul/action name', data)でvuexのactionにアクセスできる。
store.actions
- 第一引数はcontext 第二引数はfromt側から送られてきたデータ
- async awaitでPromiseオブジェクトを受け取り、backend側のデータを受け取る。
- mutationsを呼び出す際はcontext.commitで呼び出す。第1引数にmutationMethod、第2引数にpromiseオブジェクトのデータ
store.js
const actions = {
aysnc login(context, data) {
const response = await axios.post('api', data);
context.commit('setUser', response.data)
}
}
front側
- front側でactionsとアクセスする際は$store.despatch()を持ちいいる。
- 第1引数はactionMethod, 第2引数はdata
export default {
data() {
return: {
userDate: {
name: '',
password: ''
}
}
},
method: {
async login() {
//store.jsにてnamespaced:trueにしておけばnamespaceが付与できfaileの分割ができる(余談)
await this.$store.dispatch('auth/login', this.userData);
this.$router.push('/');
}
}
}
getters
gettersはstateを参照する為のもの
store.js
const getters = {
userName: state => state.user? state.user.name : "";
}
参照方法はstore.gettersで行う。モジュール設定をしている場合配列で’モジュール名/メソッド名’でアクセスできる
export default {
computed: {
isLogin () {
this.$store.getters['auth/username'];
}
}
}
login状態を維持する
vueの使用上、リロードをすると、再度Vueインスタンスが生成され、storeでのstateは破棄されます。
その為、vueインスタンが生成され前にloginUsaerを取得してその後インスタンスを生成する手順をふむことで解決できます。
まずはAPI
LoginUserを取得
routes/api.php(laravel)
//get currentUser
Route::('/current_user', fun() => Auth::User())->name(''crrent_user');
続いてstoreの記述
actionsにて非同期処理を記述する。
const actions = {
async currentUser(context) {
const response = await axios.get('api/current_user');
//apiでuserdataが取得できていたら、そのまま変数に格納、なければ、nullを格
const user = reponse.data || null;
//contextでmuutationメソッドを呼び出し、stateの更新。
context.commit('setUser', user);
}
}
最後にapp.jsにてactionの呼び出し
非同期処理にてアクションを呼び出す。
const createApp = async () => {
await store.dispatch('auth/currentUser')
const app = new Vue({
el: '#app',
render: h => h(App),
router,
store,
});
createApp()
login状態は維持できるが、直接URLを打てば、LoginComponentにアクセスできます。
なのでこれを抑止する為にナビゲーションガードを使用します。
またあapp.jsで呼び出したdispatchの非同期処理は処理が完了する前にメインスレッドが進み、vueインスタンスが生成されてしまします。このタイムラグがあることで数秒間ん印象状態が維持できない状態になり、この状態でナビゲーションガードをせってしても処理をすり抜けてしまいます。なのでナビゲーションガード自体にsetTimeoutを設定してこの問題を回避します。
navgation gruadの設定
import store from './store'
{
name: "login",
path: "/login",
component: Login,
beforeEnter: (to, from, next) => {
setTimeout( () => {
if (store.getters['auth/check']) {
next('/')
} else {
next()
}
}, 3000)
}
},
##終わりに
備忘録としては終了しますが、学習を深めれば再度更新を行っていきます。