LoginSignup
1
1

More than 1 year has passed since last update.

ブログ編集画面での画像表示

Last updated at Posted at 2022-04-06

目次

1.元の記事にサムネイルがあるかどうかで分岐する
2.条件付きレンダリング
3.削除後の動き

Laravel + Vue.js を使ったブログ開発で、
ブログ編集画面に編集前記事のサムネイルを表示させる機能を作ったのでアウトプットとして記事を書いてみました。

編集画面で、やっぱりサムネイルを別の画像に変更したい!という時ってありますよね!
編集画面に画像を表示させ、削除して別の画像に変更するという機能を付けてみました。

1. 元の記事にサムネイルがあるかどうかで分岐する

まずは元の記事にサムネイルがあるかどうかで条件分岐します。
サムネイルがないのに、サムネイル変更ボタンがあったら不自然ですよね

というわけで、
サムネイルが無い場合 -> サムネイル選択ボタン
サムネイルがある場合 -> サムネイル表示 & サムネイル変更ボタン
という仕組みにしていきます!

2. 条件付きレンダリング

Vue を使用した開発なので、
v-if v-else を使って書いていきます。

サムネイルが無い場合

EditComponent.vue
<div
    v-show="reShow"
    v-if="images.length === 0"
    class="form-group"
>
    <label for="exampleFormControlFile1">サムネイル</label>
    <input
        type="file"
        ref="file"
        class="form-control-file"
        id="exampleFormControlFile1"
        name="imageData"
        accept="image/*"
        v-on:change="onFileChange"
    />
</div>

サムネイルがある場合

EditComponent.vue
<div v-else v-show="show" class="form-group">
    <label for="exampleFormControlFile1">サムネイル</label>
    <div v-for="(image, index) of images" :key="index">
        <img
            v-for="(image, index) of images"
            :key="index"
            :src="'/storage/image/' + image.image"
            style="width: 200px"
        />
        <button
            v-show="show"
            @click="resetThumbnail()"
            class="btn btn-outline-danger"
        >
            削除
        </button>
    </div>
</div>

<div v-for="(image, index) of images" :key="index">

これを使うために、blade 側で 下記を定義します。

edit.blade.php
<edit-component 
    v-bind:post="{{ json_encode($post) }}"
    v-bind:images="{{ ($post->images) }}"
>
</edit-component>

これによって、
サムネイルが無い場合
スクリーンショット 2022-04-05 15.40.04.png

サムネイルがある場合
スクリーンショット 2022-04-05 15.38.24.png

こんな感じになります!

3. 削除後の動き

ただ、削除後も削除ボタンが残っていては不自然ですよね。
そのため、

<button
    v-show="show"
    @click="resetThumbnail()"
    class="btn btn-outline-danger"
>
    削除
</button>

このように v-show="show"を使い、
@click="resetThumbnail()"が作動したら
画像削除と同時に、this.show = !this.show; が走るようにしてあります。

EditComponent.vue
methods: {
    resetThumbnail(images) {
        this.show = !this.show;
        const id = this.images.map((item) => item.id);
    
        axios.delete("/images/" + id).then((res) => {
            console.log(res);
        });
    },

こんな感じです!

細かい部分は省略しましたが、大まかな流れを書いてみました!
どこか修正部分ありましたらコメントください...!

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