Vue.js?是一套構(gòu)建用戶界面(user interface)的漸進(jìn)式前端框架,因?yàn)?Vue.js 的核心庫只專注于視圖層,Vue.js 沒有內(nèi)置的 HTTP API,如果我們需要與服務(wù)器進(jìn)行交互,我們必須引入第三方的 API,Vue.js 官方推薦的 HTTP 庫是 Asios。Axios 是一個(gè)偉大的 HTTP 客戶端庫。它默認(rèn)使用 promises 并在客戶端和服務(wù)器上運(yùn)行(這使得它適合于在服務(wù)器端渲染期間獲取數(shù)據(jù))。Asios 很容易與 Vue.js 一起使用,從 WordPress Rest API 獲取數(shù)據(jù),然后通過 Vue.js 展示出來。下面我們就舉例說明,如何使用 Vue.js 和 Axios 與?WordPress Rest API?進(jìn)行交互,獲取和提交數(shù)據(jù)。
- 原文來源:wordpress智庫
最新教程如下
下面的示例中,使用了基于 Vue.js 的 Element UI 實(shí)現(xiàn)前端界面樣式,如果你熟悉其他前端框架,也可以使用其他框架(如 BootStrap)來實(shí)現(xiàn)前端界面樣式,效果是一樣的。
使用 Vue.js 和 Axios 從 WordPress Rest API 獲取數(shù)據(jù)并展示
下面的代碼通過 Rest API 獲取了 WordPress 的最新文章并以卡片的方式顯示在前端。
[wprs_c-alert type=”info” content=”下面的代碼是從一個(gè) Vue.js 單文件組件中直接復(fù)制出來的,直接粘貼到頁面中,不會(huì)顯示任何內(nèi)容,需要手動(dòng)掛載到 “#APP” 上或者通過 Vue Router 掛載才能顯示文章到頁面中。” /]
<template>
<el-row v-if="posts && posts.length">
<el-col :span="8" v-for="post of posts">
<el-card :body-style="{ padding: '0px' }">
<div style="padding: 14px;">
<span>{{post.title.rendered}}</span>
<div class="bottom clearfix">
<time class="time">{{ post.modified }}</time>
<el-button type="text" class="button">操作按鈕</el-button>
</div>
</div>
</el-card>
</el-col>
</el-row>
</template>
<script>
// 首先導(dǎo)入 axios 庫
import axios from 'axios';
export default {
data: () => ({
posts : [],
errors: []
}),
// 組件創(chuàng)建后獲取數(shù)據(jù),如果獲取成功,設(shè)置 posts 數(shù)據(jù),如果失敗,設(shè)置錯(cuò)誤數(shù)據(jù)
created() {
axios.get('http://abc.dev/wp-json/wp/v2/posts')
.then(response => {
this.posts = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
</script>
使用 Vue.js 和 Axios 提交表單數(shù)據(jù)到 WordPress Rest API
下面的示例是一個(gè)基本的?WordPress 前端投稿?表單,用戶點(diǎn)擊 “立即投稿” 后,會(huì)通過 Rest API 發(fā)布一個(gè)狀態(tài)為草稿的文章到 WordPress 后臺(tái)。通過 Rest API 到 WordPress 后臺(tái)需要驗(yàn)證才能提交,因?yàn)槭窃谕粋€(gè)站點(diǎn)提交數(shù)據(jù),我們使用最基本的 “Nonce” 驗(yàn)證方法即可。這種方法首先需要設(shè)置 nonce 隨機(jī)數(shù)到前端,以便 Axios 庫使用。先加入以下代碼到 WordPress 的 functions.php 文件中。
add_action( 'wp_enqueue_scripts', 'rest_theme_scripts' );
function rest_theme_scripts() {
wp_localize_script( 'jquery', 'wp', [
'nonce' => wp_create_nonce( 'wp_rest' ),
] );
}
上面的代碼會(huì)設(shè)置一個(gè)名稱為 “wp” 的 JavaScript 對象到頁面的 head 中,然后在下面我們就可以通過?wp.nonce
?訪問 WordPress 后臺(tái)生成的這個(gè)隨機(jī)數(shù)了,把這個(gè)隨機(jī)數(shù)加入到 Axios 的 http header 中,Rest API 會(huì)對這個(gè)隨機(jī)數(shù)進(jìn)行驗(yàn)證,如果驗(yàn)證一致,就可以保存提交的數(shù)據(jù)了,如果驗(yàn)證不通過,則返回錯(cuò)誤信息。
<template>
<el-form ref="form" :model="form" label-width="80px">
<el-c-alert v-if="message.show" :title="message.title" :type="message.type"></el-c-alert>
<el-form-item label="文章標(biāo)題">
<el-input v-model="form.title"></el-input>
</el-form-item>
<el-form-item label="文章摘要">
<el-input type="textarea" v-model="form.excerpt"></el-input>
</el-form-item>
<el-form-item label="文章內(nèi)容">
<el-input type="textarea" v-model="form.content"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">立即投稿</el-button>
<el-button>取消</el-button>
</el-form-item>
</el-form>
</template>
<script>
import axios from 'axios';
// 設(shè)置 axios 全局 header nonce 數(shù)據(jù),用于 WordPress REST Api 驗(yàn)證,
// 如果沒有這個(gè),提交數(shù)據(jù)時(shí),會(huì)因?yàn)闄?quán)限驗(yàn)證失敗而提交不了
axios.defaults.headers.post['X-WP-Nonce'] = wp.nonce;
export default {
data() {
return {
form : {
title : '',
excerpt : '',
content : '',
},
message: {
title: "",
type : "",
show : false
}
};
},
methods: {
onSubmit() {
axios.post('http://abc.dev/wp-json/wp/v2/posts', {
title : this.form.title,
excerpt : this.form.excerpt,
content : this.form.content,
})
.then(response => {
this.message.title = "保存成功";
this.message.type = "success";
this.message.show = true;
})
.catch(e => {
this.errors.push(e)
});
}
}
};
</script>
上面的代碼中,用戶提交成功后,會(huì)顯示一個(gè)提交成功的提示消息。為了精簡文章的篇幅,沒有把提交失敗的處理方法貼出來,所以如果提交失敗,不會(huì)有任何提示。有需要的朋友可以自行實(shí)現(xiàn)一下。
創(chuàng)建通用的 http 模塊,方便在各個(gè)模塊中調(diào)用
為了方便在多個(gè)模塊直接調(diào)用數(shù)據(jù),我們還可以編寫一個(gè)通用的 http 模塊,在其他模塊使用時(shí),直接引入這個(gè)模塊即可。如下:
<script>
import axios from 'axios';
export const HTTP = axios.create({
baseURL: `http://jsonplaceholder.typicode.com/`,
headers: {
Authorization: 'Bearer {token}'
}
})
</script>
在其他模塊使用時(shí):
<script>
import {HTTP} from './http-common';
export default {
data: () => ({
posts: [],
errors: []
}),
created() {
HTTP.get(`posts`)
.then(response => {
this.posts = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
</script>
熟悉上上面的開發(fā)方法以后,在 WordPress 前端頁面獲取提交數(shù)據(jù)都可以直接通過 WordPress Rest API 進(jìn)行,只要熟練 JavaScript,完全可以結(jié)合 WordPress 做一個(gè)功能豐富,界面漂亮的應(yīng)用了,比如 WordPress 使用者經(jīng)常尋找的前端用戶中心,甚至基于WordPress 的購物車訂單系統(tǒng)等,都可以通過本文介紹的方法進(jìn)行開發(fā)。