3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

初学者必見!Headerにある項目を動的に変化させる方法

Last updated at Posted at 2020-12-18

今回は、ログインしている時だけ「ログアウト」ボタンを表示させたいと思ったので、そのやり方を備忘録として書いていきます。

最後まで見て、よかったらLGTMお願いします!!(今じゃなくていいです)


それでは順を追って説明します。


Vuexの機能を使い、sotre/index.jsのstateにユーザーがログインしているかを判断するauthを設定します。

store/index.js

import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex);

export default new Vuex.Store({
  plugins: [createPersistedState()],  //永続的にログインできるプラグイン
  state: {
    auth: "", //userがログインしているか
    user: "", //user情報
  },
)}

vuex-persistedstateについてはこちらの記事でご紹介しているので、ぜひご覧ください。

次に、computedを使って、authの変更を検知します。
computedは自動で値の変更を検知してくれるので大変便利です。

components/Header.vue
<div class="headB" :class="{'open' : isClass}">
          <ul><li>
              <a @click="logoutButton" v-if="auth === true">ログアウト</a>
              <a @click="loginButton" v-else>ログイン</a>
            </li>
          </ul>
 </div>

<script>
export default{
    computed: {
      auth() {
        return this.$store.state.auth;  //store/index.jsのstateにあるauthを取得
      }
    },
}
</script>

これでログインしているときにログアウトが表示されるようになります。

これはHeaderだけでなく、他にも応用できそうですね。

以上、「Headerにある項目を動的に変化させる方法」でした。

3
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?