Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8595

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

$
0
0

こんにちは
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 --><linkhref="https://use.fontawesome.com/releases/v5.6.1/css/all.css"rel="stylesheet"><iclass="far fa-heart"@click="clickHeart":class="{ 'heart-red' : isActive }"
      >
      <spanclass="count">{{goodArticleCount}}</span></i></div></template><script>exportdefault{data(){return{goodArticleCount:0,isActive:false}},methods:{clickHeart(){if(this.isActive){this.goodArticleCount=this.goodArticleCount-1this.isActive=false}else{this.goodArticleCount=this.goodArticleCount+1this.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>importGoodButtonfrom'../components/GoodButton'exportdefault{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

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


Viewing all articles
Browse latest Browse all 8595

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>