【问题标题】:Passing axios data to view template传递 axios 数据到视图模板
【发布时间】:2019-10-25 19:32:44
【问题描述】:

我正在使用 vue.js 和 axioz 作为脚本(不是 cli 等)创建一个简单的 SPA

到目前为止,我能够从 json 中提取数据,然后对列表进行渲染和分页,当单击某个项目时,我可以通过控制台记录特定条目的数据。

HTML

<!--app-->
<div id="app">

    <!--articles-->
    <div class="row" style="background: #111; padding: 8em 0; width: 50%;">
            <div class="ctr">
                <div class="row articles page_content" style="padding: 0;">
                    <ul>
                        <li v-for="(post) in displayedPosts" @click="getSingle(post.id)">
                            <router-link :to="{ path: '/post/'+ post.id}" class="flex" >
                                <div class="row article_thumb">
                                    <img :src="post.url" :alt="post.title"/>
                                </div>
                                <div class="row article_excerpt">
                                    <h3 class="title">{{post.title }}</h3>
                                </div>
                            </router-link>
                        </li>
                    </ul>
                </div>
                <div class="row pagination">
                    <button type="button" v-if="page != 1" @click="page--"> << </button>
                    <button type="button" v-for="pageNumber in pages.slice(page-1, page+5)" @click="page = pageNumber"> {{pageNumber}} </button>
                    <button type="button" @click="page++" v-if="page < pages.length"> >> </button>
                </div>
            </div>
        </div>
        <!--articles-->

        <div class="row" style="background: #000; padding: 8em 0; width: 50%;">
            <div class="flex router">
                <router-view></router-view>
            </div>
        </div>

</div>
<!--app-->

VUE.JS

const Home = {
  template: "<div><h1>Click an article to update this view</h1></div>"
};

//post
var Post = {
  template:
    '<div class="row"><h1>Display data for Post ID  # {{$route.params.id}} here</h1><p style="color: red;">This is where I am stuck, cant display the post data, see example below.</p><p>{{title}}</p></div>',

  //post methods
  methods: {
    //get single post
    getSingle: function(id) {
      var self = this;
      this.id = this.$route.params.id;
      this.title = this.title;
      axios
        .get(this.baseUrl, {
          params: {
            id: this.id,
          }
        })
        .then(response => {
          this.post = response.data;
          this.title = response.data.title;
          console.log(this.title);
          console.log(this.post);
          console.log("You clicked post ID #" + this.id);
        })
        .catch(response => {
          console.log(error);
        });
    }
  },
  //post methods

  //post data
  data() {
    return {
      baseUrl: "https://jsonplaceholder.typicode.com/photos",
      posts: [],
      title: this.title
    };
  },

  //post created
  created() {
    this.getSingle(this.$route.params.id);
  },

  watch: {
    "$route.params": {
      handler(newValue) {
        const { id } = newValue;
        this.getSingle(id);
      },
      immediate: true
    }
  }
};
//post

//router
const router = new VueRouter({
  routes: [
    { path: "/", component: Home },
    { path: "/post/:id", component: Post }
  ]
});

//initial state
var paginationApp = new Vue({
  el: "#app",
  router: router,
  data: {
    posts: [],
    baseUrl: "https://jsonplaceholder.typicode.com/photos",
    page: 1,
    perPage: 2,
    pages: []
  },

  //initial state methods
  methods: {

    //get single
    getSingle() {},

    //get posts
    getPosts() {
      axios
        .get(this.baseUrl)
        .then(response => {
          this.posts = response.data;
        })
        .catch(response => {
          console.log(response);
        });
    },

    //set pages
    setPages() {
      let numberOfPages = Math.ceil(this.posts.length / this.perPage);
      for (let index = 1; index <= numberOfPages; index++) {
        this.pages.push(index);
      }
    },

    //paginate
    paginate(posts) {
      let page = this.page;
      let perPage = this.perPage;
      let from = page * perPage - perPage;
      let to = page * perPage;
      return posts.slice(from, to);
    }
  },

  //created
  created() {
    this.getPosts();
  },

  //watch
  watch: {
    posts() {
      this.setPages();
    }
  },

  //computed
  computed: {
    displayedPosts() {
      return this.paginate(this.posts);
    }
  }
});
//initial state

或查看此代码笔以获取完整示例 https://codepen.io/flashvenom/pen/YozyMx,并务必查看控制台日志。

我的问题是我无法控制台记录数据对象的标题或任何内部字段,因为我希望能够将标题等添加到视图区域中。

任何帮助或指点将不胜感激。

【问题讨论】:

标签: javascript json vue.js axios


【解决方案1】:

响应为数组形式,如果不循环数组,则无法访问数组对象元素。

如果你想得到第一篇文章的标题,那么你可以如下图所示,

this.title = response.data[0].title

要访问所有帖子标题,您可以在 vue 模板中使用 v-for 循环。下面是一个小例子,说明如何做到这一点,

<div v-for="post in posts">
    <span>{{ post.title }}</span>    
</div>

【讨论】:

  • 感谢您的快速响应,是的,这很有意义,所以我想如果我的对象 ID 从 0 开始,我可以执行类似的操作,``` this.id = this.$route.params 。ID; this.title = response.data[this.id].title ```
  • 欢迎您。是的,您可以这样做,或者可能是这样 (stackoverflow.com/questions/53033111/…) 可以帮助您在点击事件中显示单个帖子数据。
  • 我已经尝试过并且很好用,谢谢,如果你想检查一下,笔也更新了,我想我现在需要做的一件事是弄清楚如何使 id 0 动态匹配单击项目的 id,否则非常感谢几天来一直试图在 vue 论坛上得到答案
  • 真是个笨蛋,刚刚意识到,因为我已经选择了 id 始终为 0 的对象,所以完全按照我的需要工作,非常感谢,非常感谢。
  • 是的,数组的id默认从0开始。你是最受欢迎的芽。继续编码!
猜你喜欢
  • 2020-03-19
  • 2019-02-16
  • 1970-01-01
  • 1970-01-01
  • 2011-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-19
相关资源
最近更新 更多