0

this is my comment vue file

  <div>
    <button @click="getComments()" class="btn btn-primary">
      댓글 불러오기 글번호 {{ post.id }}
    </button>

    <!-- Button trigger modal -->

    <button
      @click="openWriteComment()"
      type="button"
      class="btn btn-primary"
      id="openModalBtn"
      data-bs-toggle="modal"
      data-bs-target="#exampleModal"
    >
      Write Comment
    </button>

    <!-- Modal -->
    <div
      class="modal fade"
      id="modalBox0"
      tabindex="-1"
      aria-labelledby="exampleModalLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
              aria-label="Close"
            ></button>
          </div>
          <div class="modal-body">
            <input
              type="text"
              id="modalInput"
              value="댓글을 입력해 주세요."
              v-model="comment"
            />
          </div>
          <div class="modal-footer">
            <button @click="saveComment()" class="btn btn-primary" id="saveBtn">
              Save changes
            </button>
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
              Close
            </button>
          </div>
        </div>
      </div>
    </div>
    <comment-item
      v-for="(comment, id) in comments.data"
      :key="id"
      :comment="comment"
      :getget="getComments"
    ></comment-item>

    <pagination
      @pageClicked="getPage($event)"
      v-if="comments.data != null"
      :links="comments.links"
    />
  </div>
</template>
<script>
import CommentItem from "./CommentItem.vue";
import Pagination from "./Pagination.vue";
export default {
  components: { CommentItem, Pagination },

  data() {
    return {
      comments: [],
      comment: "",
    };
  },

  props: ["post", "loginuser"],

  methods: {
    getPage(url) {
      axios
        .get(url)
        .then((res) => {
          this.comments = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    getComments() {
      axios
        .get("/commentlist/" + this.post.id)
        .then((res) => {
          this.comments = res.data;
          console.log(this.comments.data);
        })
        .catch((err) => {
          console.log(err);
        });
      // 서버에 현재 게시글의 댓글 리스트를 비동기적으로 요청
      // 즉 ,axios 를 이용해서 요청
      // 서버가 댓글 리스트 주면 , this.comments 에 할당.
    },

    openWriteComment() {
      $("#openModalBtn").on("click", function () {
        $("#modalBox0").modal("show");
      });
    },

    saveComment() {
      $("#saveBtn").on("click", () => {
        axios
          .post("/commentSave/" + this.post.id, {
            comment: document.getElementById("modalInput").value,
          })
          .then((res) => {
            this.getComments();
            this.comment = "";
            $("#modalBox0").modal("hide");
          })
          .catch((err) => {
            console.log(err);
          });
      });
    },
  },
};
</script>

this is my comment's controller

<?php

namespace App\Http\Controllers;

use App\Models\Comment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CommentsController extends Controller
{

    public function index_test()
    {
        /*
            select * 
            from comments
            where post_id = $post->id;
        */
        // return $post->comments;
        // post eloquent->class 에 comment 메서드를 구현해야함.
    }
    public function index($postId)
    {

        $comments = Comment::with('user')->where('post_id', $postId)->latest()->paginate(5);


        //지연로딩 필요한 이유
        //클라이언트에서는 $comments 가 갈때, with 안해주면 user와 연관된 정보가 안감

        return $comments;
        /*
            order by created_at desc;

        */
    }


    public function store(Request $request, $post)
    {
        $comments = new Comment();
        $request->validate(['comment' => 'required']);


        /*
 $this->valudate($request,['comment'=>'required'])
        */

        $comments->comment = $request->comment;
        $comments->user_id = Auth::user()->id;
        $comments->post_id = $post;

        $comments->save();



        return $comments;


        /*
            $comments =  Comment::create(['comment'=>request->input('comment'),
            'user_id'=> //로그인유저id
            ..
            ])
            return $comments;


            create 에 사용할수있는 칼럼은
            엘로컨트 모델 클래스에 protected $fillable 에 명시되야함.

        */
    }

    public function update(Request $request, $id)

    {
        $comments = Comment::find($id);
        $comments->comment = $request->commentInfo;
        $comments->save();



        return $comments;


        /*
                $comment->update(['comment'=>$request->input('comment')])
                할때도 , 칼럼들은 fillable에 있어야함

        */
    }
    public function destroy($id)
    {
        Comment::find($id)->delete();


        return 1;
    }
}

if i try to add comment, first time i need to click save button twice. (if i click one time, nothing change) and comments save twice

if i try to add comment second time, i need to click save button twice. and comments save third times

if i try to add comment third time, i need to click save button twice. and comments save fourth times (x4)

does anyone knows how to solve this problem??

1 Answer 1

1

Because you're trigging the save button twice. Try it like this:

<button @click.prevent="saveComment()" class="btn btn-primary">
     Save changes
</button>

Then in your method:

saveComment() {
    axios.post("/commentSave/" + this.post.id, {
       comment: this.comment,
    })
    .then((res) => {
       this.getComments();
       this.comment = "";
       $("#modalBox0").modal("hide");
     })
     .catch((err) => {
        console.log(err);
     });
   },

I also recommend you to avoid using JQuery in your Vue code. In-fact that will lead you to lose the full benefits of using Vue.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks a lot. but i can's understand with your answer's last line :: lead you to lose the full benefits of using Vue. what benefits can i lose if i use JQuery with vue.js?
You must understand that this modern JS framworks exists to replace JQuery and give a better developing experience.
My advice was to never use them together (Better to remove JQuery for good) ex: $("#saveBtn").on("click", () => {} ) , it can be replaced just by @click= so basically, you will never need to access the DOM with getElementById..etc and all that crap 😊

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.