2
1

More than 3 years have passed since last update.

【Vue.js】メニュー機能の実装 実装編 rails6

Last updated at Posted at 2021-01-03

はじめに

クリックするとメニューが開いたり閉じたりする機能をVue.jsで実装します。
この記事では、rails6で実装してますので、導入につまずいてる方がいらっしゃったら、下記の「Vue.js導入編」をご参照ください。

【Vue.js】メニュー機能の実装 Vue.js導入編 rails6
https://qiita.com/AKI3/items/e87203c590322c908946

目次

1.Vue.js
2.html
3.scss

開発環境

Vue 2.6.12
rails 6.0.0
ruby 2.6.5

実装

それでは実装していきます〜

1. Vue.js

app/javascript/packs/menu_vue.js
const app = new Vue({
  el: '#app',
  data: {
    ActiveBtn: false
  },
})

Veu.js自体の実装は簡単です。

2. html

app/views/tops/new.html.erb
<div class="top-editor-wrap">
  <div id="app">
    <!--メニューのボタン-->
    <div class="top-editor_btn" v-on:click='ActiveBtn=!ActiveBtn'> ←ここがveu.js
      <h1>ボタン</h1>
    </div>
    <!--サイドバー-->
    <transition name="editor-side">
      <div class="editor-side" v-show="ActiveBtn"> ←ここがveu.js
        <div class="editor">
          <h3>メニュー</h3>
          <p>項目1</p>
          <p>項目2</p>
          <p>項目3</p>
        </div>
      </div>
    </transition>
  </div>
</div>

v-on:click='ActiveBtn=!ActiveBtn'が、ボタンがクリックされたらActiveBtnの真偽値を逆にする(反転する)という記述。

3. scss

app/assets/stylesheets/editor.scss
.top-editor_btn {
  position: fixed;
  top: 30px;
  left: 40px;
  cursor: pointer;
  z-index: 50;
}

.top-editor_btn img {
  width: 65px;
}

.editor-side {
  position: fixed;
  background-color: hsla(0, 0%, 57%, 0.829);
  z-index: 30;
  width: 325px;
  height: 100vh;
  top: 0;
}

以上で完成です!!

まとめ

この機能ではActiveBtnがポイントでした。
もちろんJSだけ同じ機能を作る事は可能ですが、Veu.jsを使用するメリットはコードの量が圧倒的に減る事でした。
まだまだ勉強しはじめたばかりなので、さらに学んで行きたい思ってます〜

最後に

私はプログラミング初学者ですが、同じ様に悩んでる方々の助けになればと思い、記事を投稿しております。

それでは、また次回お会いしましょう〜

参考

【公式】
https://jp.vuejs.org/v2/guide/

【Vue.js】メニュー機能の実装 Vue.js導入編
https://qiita.com/AKI3/items/e87203c590322c908946

大変参考にさせていただきました。ありがとうございます。
https://qiita.com/helloworld193/items/9aed3870be1e739c3ad2

ともすたの谷口さん
https://www.youtube.com/playlist?list=PLh6V6_7fbbo-SZYHHBVFstU2tp0dDZMAW

2
1
2

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