Construction of Single Page Application Based on Vue.js and WordPress Rest API

Keywords: Javascript Vue axios REST JSON

Preface

Vue.js is a library for building interactive Web interfaces. It provides MVVM data binding and a composable component system with simple and flexible API.
axios is an HTTP client based on Promise for browsers and nodejs, which we will use to request api s.
The WordPress REST API provides API endpoints for WordPress data types, allowing developers to interact remotely with sites by sending and receiving JSON (JavaScript Object Notation) objects.

demo needs to implement functions

  • Get a full list of articles
  • Click on View Details to enter the article details page to show the article content.
  • Implementing Paging Function of List of Articles
  • Get all articles categorized
  • Click on Categories to Get Lists of Articles under Different Categories

Environment building

Scaffold architecture for vue-cli single-page applications:

https://cn.vuejs.org/v2/guide/installation.html

Introduction of Axios

https://www.kancloud.cn/yunye/axios/234845

element-ui introduction

http://element-cn.eleme.io/2.0/#/zh-CN/component/installation

Tools for testing API s

https://www.getpostman.com/

Wordpress REST API Manual

https://developer.wordpress.org/rest-api/

Create two new. vue files to display the list of articles and the details of articles respectively

List of articles: articleList.vue
Article details: article.vue
In src/router.js, page routing is set as follows:

import Vue from 'vue'
import Router from 'vue-router'
import ArticleList from '@/components/articleList'
import Article from '@/components/article'
Vue.use(Router)
export default new Router({
    routes: [
        {
            path: '/',
            name: 'ArticleList',
            component: ArticleList
        },
        {
            path: '/article/:id',
            name: 'Article',
            component: Article
        },
    ]
})

articleList.vue structure:

<template>
    <el-row>
        <el-col>
            <el-col class="article">
                <ul>
                    <li>
                        <h1>Article title</h1>
                        <div>Article description</div>
                        <span>View details</span>
                    </li>
                </ul>
            </el-col>
        </el-col>
    </el-row>
</template>
<script>
    export default {
        data () {
            return {                
            }
        },
    }
</script>
<style lang="less">  
</style>

article.vue structure:

<template>
    <el-row>
        <el-col class="article">
            <h1>Title</h1>
            <p class="p"><span>Author:</span><span>Release time:</span></p>
            <div></div>
        </el-col>
    </el-row>
</template>
<script>
    export default {
        data () {
            return {
            }
        },
    }
</script>
<style lang="less">
</style>

The article list api gets:

New api/api.js file under src directory, pay attention to replacing domain name

import axios from 'axios';
let base = 'http://example.com/wp-json/wp/v2';
//Get a list of articles
export const getArticleList = params => {
    return axios.get(`${base}/posts`, params).then();
};

Introduce api.js in articleList.vue:

import {getArticleList,getCategories} from '../api/api';

Define the request event and execute the event when the page is loaded. Finally, define an array to store the data returned from the request.

data () {
    return {
        articleData: [{
            title: {
                rendered: ''
            },
             excerpt: {
                rendered: ''
            }
        }],
    }
},
mounted: function () {
    this.getarticlelist()
    this.getcategories()
},
methods: {
    getarticlelist(){
        getArticleList().then(res => {
            this.articleData = res.data
        })
    },
}

Rendering data to pages using v-for

<ul>
    <li v-for="(item,index) in articleData">
        <h1 v-html="item.title.rendered"></h1>
        <div v-html="item.excerpt.rendered"></div>
        <span>View details</span>
    </li>                
</ul>

Here's a simple display of the list of articles to complete the function

Article Details Page

Bind events for view details in the article list:

When clicked, get the current click article id and jump to the details page of the response according to different IDS

<span @click="article(index)">View details</span>
article(index){
    let ids = this.articleData[index].id
    this.$router.push({
        path: '../article/' + ids
    })
},

Now that we have clicked to jump to the article details page, the next thing we need to do is to display the content of the article under the current id in the details page. We need to execute the event to get the content of the article when the current details page is loaded.
Define an API in api.js to get the details of the article

//Get a single article
export const getArticle = ids => {
    return axios.get(`${base}/posts/${ids}`).then(res => res.data);
};

Events are introduced and defined in article.vue:

import {getArticle} from '../api/api';
getarticle(){
    //Get id
    let ids = this.$route.params.id
    //Use the acquired id to request the api
    getArticle(ids).then(res => {
        this.articleData = res
    })
},

Binding events and rendering article structures

<el-col class="article">
    <h1 v-html="articleData.title.rendered"></h1>
    <p class="p"><span>Author:{{articleData.author}}</span><span>Release time:{{articleData.date}}</span></p>
    <div v-html="articleData.content.rendered"></div>
</el-col>

Implementation of Paging List of Articles

element-ui Paging Component:

<el-pagination 
    layout="prev, pager, next" :page-size="per_page"
    :total="total" @current-change="handleCurrentChange">
</el-pagination>

The handleCurrentChange event is defined in the above component to take different parameters for the requested api when clicking on different pages

Request parameters

Page: Specifies the result page to be returned.
For example, / wp/v2/posts?page=2 is the second page of the post result.
per_page: Specifies the number of records to be returned in a request, an integer from 1 to 100.
For example, / wp/v2/posts?per_page=1 only returns the first post in the collection. To determine how many pages of data are available, the API returns two title fields, each paging response.
The api returns the parameters of the headband:
X-WP-Total: Total number of records in a collection
X-WP-Total Pages: Total number of pages containing all available records
The method of requesting the list of articles API has been defined. It only needs to be modified and called. It needs to pass two parameters page and per_page to the api. The value of page needs to be obtained from the paging component, and per_page needs to be set.
After the api request succeeds, you can find the X-WP-Total field in the header, which is the total number of articles we need, because the format of the field X-WP-Total can not get the value directly, so you need to convert it to an array first and then take the value.
Modified method of api request:

let params = {
    page: this.page,
    per_page: this.per_page,     
}
getArticleList({params}).then(res => {
    let headerData = Object.values(res.headers)
    this.articleData = res.data
    this.total = parseInt(headerData[2])
                 
})          

Called in Paging Events

handleCurrentChange(val) {
    this.loading = true
    this.page = val
    this.getarticlelist()
},

Get all articles categorized

It's easy to get all the classifications, just use v-for rendering to get the data.

api.js

//Getting Article Categories
export const getCategories= params => {
    return axios.get(`${base}/categories`, params).then(res => res.data);
};

html

<ul>
    <li v-for="item in categoriesData">{{item.name}}
    </li>
</ul>

js

mounted: function () {
    getcategories(){
        getCategories().then(res => {
            this.categoriesData = res
        })
    }
}        

Click on Categories to Get Lists of Articles under Different Categories

Add Click Events

Add click events for each category and styles for the selected category

<ul>
    <li v-for="(item,index) in categoriesData" @click="categorie(index)"
                        :class="{ 'active': active == index }">{{item.name}}
    </li>
</ul>

Revamp article list request api

Add a category field to the article list request api, which is the id of the required category

let params = {
    page: this.page,
    per_page: this.per_page,
    categories: this.categories
}

Writing events

There are several things you need to do when clicking on an event:

  • Get the current click classification id
  • Add the selected style for the current classification
  • Let the page field in the request be 1
  • Get the result of the request and re-render the list of articles
categorie(index){
    this.categories = this.categoriesData[index].id
    this.page = 1
    this.active = index
    this.getarticlelist()
}

Server deployment

npm run dev is executed under the root directory to generate dist static folder. The contents of dist folder can be deployed on http server and accessed by domain name.

demo address

https://github.com/qianxiaoduan/Vue-WordPress-Rest-API
http://vue-blog.qianxiaoduan.com/

Permanent link: https://blog.qianxiaoduan.com/archives/134

Posted by spawnark on Wed, 11 Sep 2019 00:23:53 -0700