LoginSignup
0
0

More than 3 years have passed since last update.

Vue.jsで簡易的ないいねボタン

Posted at

こんにちは
Vue.jsに関して色々調べながら書いてます。
備忘録で簡易的にコンポーネントに関して色々勘違いしていたので
書き直してみました。
(触り始めたばっかなので間違ったらそっと教えていただければと思います!)

vue-cliでのプロジェクトの作成やらは省きます。
(いっぱい記事あったので書いても意味ないかなと🤔)

環境

vue/cli 4.4.6
vue: 2.6.11
FontAwsome(アイコンで使いました。CDNでやっちゃってます)

ディレクトリ

スクリーンショット 2020-08-27 22.59.41.png

この画像のWEB以下のcomponentsとviewsを使います。(あとrouter)
(Javaのプロジェクトも混ざってるのでbuile.gradelとか余計なファイルもあります🙇‍♂️)

components

componentsのディレクトリの下に"goodButton.vue"というファイルを作成します。
src/
    ├ components/
                        └ GoodButton.vue


<template>
  <div>
    <!-- fontawsomeのCDN -->
    <link href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" rel="stylesheet">
    <i
      class="far fa-heart"
      @click="clickHeart"
      :class="{ 'heart-red' : isActive }"
      >
      <span class="count">{{ goodArticleCount }}</span>
    </i>
  </div>
</template>

<script>
export default {
  data () {
    return {
      goodArticleCount: 0,
      isActive: false
    }
  },
  methods: {
    clickHeart () {
      if (this.isActive) {
        this.goodArticleCount = this.goodArticleCount - 1
        this.isActive = false
      } else {
        this.goodArticleCount = this.goodArticleCount + 1
        this.isActive = true
      }
    }
  }
}
</script>

<style>
  .fa-heart {
    font-size: 20px;
    margin-left: 35px;
    color: #5F5B5B;
    position: absolute;
    top: 150px;
    left: 700px;
  }

   .count {
    color: #5F5B5B;
  }

  .heart-red {
    color: red;
  }
</style>

ボタン押したらカウントが0から1になる。
もう一度押したら1から0になる。
ハートのアイコンが灰色から赤色になるという処理を書いてます。
(めちゃくちゃ簡単に書いてます。バックエンドのこととかは意識してません)

views

次にGoodButton.vueをviewsの下に作成したgoodButtonResult.vueにてimmportし、
componentとして利用します。

src/
    ├ components/
                        └ GoodButton.vue
    │
    ├ components/
                        └ goodButtonResult.vue

<template>
  <div>
    <good-button></good-button>
  </div>
</template>

<script>
import GoodButton from '../components/GoodButton'
export default {
  components: {
    'good-button': GoodButton
  }
}
</script>

結果

スクリーンショット 2020-08-28 14.42.20.png
スクリーンショット 2020-08-28 14.42.13.png

クリックすると赤くなり1カウントされます。

命名規則とかも注意した方が良いかも🤔

👇のQiita参考にしました(ドキュメントにも同じように書いてあったような)
https://qiita.com/ngron/items/ab2a17ae483c95a2f15e

引用
https://jp.vuejs.org/v2/guide/components.html

まだまだ不足してる情報等発見したら書き足すか別記事にて🙇‍♂️

0
0
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
0