简体   繁体   English

如何向ajax api vue js显示一些用户帖子

[英]how to show some user posts to ajax api vue js

i just display 5 users post in modal我只在模态中显示 5 个用户帖子

html html

<div id="app">
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user,i in users">
          <td> <b-button v-b-modal.modal-1 v-on:click="Showpost(user.id, i)">{{user.id}}</b-button></td>
          <b-modal  id="modal-1" title="info" >
            <p class="my-4">{{posts.title}}</p>
          </b-modal>
          <td>{{user.name}}</td>
        </tr>
      </tbody>
    </table>
  </div>

js js

new Vue({
  el: "#app",
  data: {
    users: [],
    posts: [],
  },
  methods: {
    Showpost(id,i) {
      console.log("id",id);
      console.log("i",i)
      fetch("https://jsonplaceholder.typicode.com/posts?userId=" + id)
        .then(response => response.json())
        .then((data) => {
          this.posts = data[i];
        })
    },
  },
  computed: {
    object: function(){
      return this.posts.filter(function(post){
        return post.userId >= 5
      })
    },
  },
  mounted() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(response => response.json())
      .then((data) => {
        this.users = data;
      })
  },
});

i will do so simple code to clear how this should be done我会做这么简单的代码来清除这应该如何完成

at first首先

<tbody>
    <tr v-for="(user,index) in users">
      <td> <b-button v-b-modal.modal-1 v-on:click="showUserPosts(user.id,index)">{{user.id}}</b-button></td>
      <b-modal  id="modal-1" title="info" >
      </b-modal>
      <td>{{user.name}}</td>
    </tr>
  </tbody>

then instead of然后代替

      this.posts = data[i];

do it

      this.posts = data;

and in your html under the table tag do并在您的 html 中的 table 标签下做

<p v-for="(post,index) in posts" v-text="post.title"></>

if you want just show one post not many make如果您只想显示一个帖子,则不会很多

data:function {
return{
users: [],
posts: {},
}
 },

and

<p v-if="post.title" v-text="post.title"></>

I hope this help you.我希望这对你有帮助。 Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM