首页 > 解决方案 > How to declare condition statement in nuxt js

问题描述

I display data using Wordpress API in nuxt js. I try to display data in category wise example where ('post.category ', '=', 'categoryName ') what is the syntax in vuejs/nuxtjs.

Is it even possible?

script:

import axios from 'axios'
export default {
  data() {
    return {
      posts: []
    }
  },
  asyncData() {
    return axios.get('http://localhost/wordpress/wp-json/wp/v2/posts')
      .then(res => {
        return {
          posts: res.data
        }
      })
  }
}

template

<div class="col-lg-4" v-for="post in posts" :key="post.id">
    <div class="news-post image-post">
        <img :src="post.fi_300x180">
        <div class="hover-post text-center">
            <a class="category-link" href="#">Travel</a>
            <h2><a href="single-post.html">{{post.slug}}</a></h2>
            <ul class="post-tags">
                <li>by <a href="#">Stan Enemy</a></li>
                <li>3 days ago</li>
            </ul>
        </div>
    </div>
</div>

标签: javascripthtmlvue.jsnuxt.js

解决方案


如果我正确理解了您的问题,您是否想用来自您的 axios 获取请求的响应填充帖子数组?

如果是这样,那么您可以按如下方式执行此操作:

<template>
    <div>
        <p v-if="loading">Loading posts...</p>
        <div v-for="post in posts" :key="post.id">
            <h3>{{ post.title }}</h3>
            <p>{{ post.snippet }}</h3>
        </div>
    </div>
</template>

<script>
import axios from 'axios'

export default {
    data() {
        return {
            posts: [],
            loading: false
        }
    },
    created() {
        this.fetchData()
    }
    methods: {
        fetchData() {
            this.loading = true
            axios
                .get('endpoint')
                .then(res => {
                    this.posts = res.data.posts
                    this.loading = false
                })
                .catch(error => {
                    //handle error
                })
        }
    }
}
</script>

我使用 setTimeout 函数重新创建了它来模拟对 api 的调用。

https://jsfiddle.net/5b9ofqgh/


推荐阅读