LoginSignup
0
1

More than 3 years have passed since last update.

[メモ]ログイン情報をページ読み込み時に一度だけ呼び出す

Posted at

概要

ページを読み込んだときに必要なデータをgetする際に、mounted()から呼び出すことがあると思います。
mountedはコンポーネントが呼び出されるたびに実行されるので、
コンポーネントA→コンポーネントB→コンポーネントAとページ遷移したらコンポーネントAのmountedは二回呼び出されることになります。
しかし、ページ遷移するたびにmountedすると時間もかかってしまうので、1回目のコンポーネントを読み込んだ時だけmountedを呼び出そうと思います。

解決策

ログインユーザーの情報を呼び出したいと思います。

auth.js
//ログインしているユーザー情報を取得するメソッドです
const state = {
    user: null,
};
const getters = {
    user: state => state.user ? state.user: '',
};
const mutations = {
    setUser(state,user){
        state.user = user;
    },
};
const actions = {
    async fetchUser(context){
        await axios.get('/api/user', {
            headers: {
                Authorization: `Bearer ${state.token}`
            }
        }).then((result)=>{
            context.commit("setUser", result.data.user);
        }).catch(error=>{
            console.log(`Error! HTTP Status: ${error}`);
        })
    },
}

改善前

<script>
computed: {
    user(){
        return this.$store.getters["auth/user"];
    },
},
mounted() {
    console.log('mounted start!');
    this.$store.dispatch('auth/fetchUser'); //上記のメソッド呼び出し
}
</script>

改善後

<script>
mounted() {
    console.log('mounted start!');
    const user = this.$store.getters["auth/user"]; 
    if(!user){ //gettersにログインユーザー情報が入っていない場合だけ呼び出す
         this.$store.dispatch('auth/fetchUser');
    }
}
</script>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1