首页 > 解决方案 > 我正在尝试将用户 ID 从我的刀片模板传递给 Vue,以便将 Axios 发布请求发送到服务器

问题描述

但是,当我单击按钮时,只有第一个按钮包含用户 ID,其余按钮返回 null。还取决于我在 HTML 上放置 id 标签的位置,它data-id是空的。如何将我的刀片视图中的数据传递给 Vue.js,以获取包含帖子 ID 的 Axios 帖子请求?

const app = new Vue({
  el: '#like',
  data: {
    post_id: '',
  },

  methods: {
    whichId: function(event) {
      this.post_id = this.$el.getAttribute('data-id');
      console.log(this.$el.getAttribute('data-id'));
    }
  }
})
<div class="container" id="like">
  <table class="table mt-5">
    <tbody>
      @foreach ($posts as $post)
      <tr>
        <td><img src="images/profil.svg" class="rounded-circle border border-dark ml-2" width="60" height="60" alt=""></td>
        <td>{{ $post->username->name }}</td>
        <td>{{ $post->content }}</td>
        <td>
          <button v-on:click="whichId" data-id="{{ $post->id }}">
            <img src="/images/heart.svg" width="30" height="30" />
          </button>
        </td>
        <td>{{ $post->created_at->diffForHumans() }}</td>
      </tr>
      @endforeach
    </tbody>
  </table>
</div>

标签: laravelvue.jsaxioslaravel-blade

解决方案


thethis.$el将引用元素。使用 PHP 遍历记录时。您应该通过单击事件处理程序传递 id。感谢 laracast 上的 Wilk Randall 的帮助。

methods: {
    whichId (postId) {
          console.log(postId);
    }
}
<td><button v-on:click="whichId({{ $post->id }})"<img src="/images/heart.svg" width="30"></button></td>


推荐阅读