基于Vue.js和WordPressRestAPI构建单页应用
时间:2023-04-02 13:10:46
HTML
前言Vue.js是一个用于构建交互式Web界面的库。它通过简单、灵活的API提供MVVM数据绑定和可组合的组件系统。axios是用于浏览器和nodejs的基于Promise的HTTP客户端,我们将使用它来请求api。WordPressRESTAPI为WordPress数据类型提供API端点,允许开发人员通过发送和接收JSON(JavaScript对象表示法)对象与站点进行远程交互。demo需要实现获取所有文章列表的功能。点击查看详情进入文章详情页面,显示文章内容。实现文章列表的分页功能。获取所有文章类别。:https://cn.vuejs.org/v2/guide/installation.htmlaxios介绍https://www.kancloud.cn/yunye/axios/234845element-ui介绍http://element-cn.eleme.io/2.0/#/zh-CN/component/installation测试API的工具https://www.getpostman.com/WordpressRESTAPI手册https://developer.wordpress.org/rest-api/新建两个.vue文件来显示文章列表和文章详情文章列表:articleList.vue文章详情:article.vue并在src/router.js中设置页面路由如下:importVuefrom'vue'importRouterfrom'vue-router'importArticleListfrom'@/components/articleList'importArticlefrom'@/components/article'Vue.use(Router)exportdefaultnewRouter({routes:[{path:'/',name:'ArticleList',component:ArticleList},{path:'/article/:id',name:'Article',component:Article},]})articleList.vue结构:article.vue结构:Title
作者:发??布时间:
文章列表api获取:在src目录新建api/api.js文件,注意替换域名importaxiosfrom'axios';letbase='http://example.com/wp-json/wp/v2';//获取文章列表exportconstgetArticleList=params=>{returnaxios.get(`${base}/posts`,params).then();};在articleList.vue中引入api.js:import{getArticleList,getCategories}from'../api/api';定义request事件,页面加载时执行事件,最后定义一个数组存放request返回的数据(){return{articleData:[{title:{rendered:''},excerpt:{rendered:''}}],}},安装:function(){this.getarticlelist()这个。getcategories()},methods:{getarticlelist(){getArticleList().then(res=>{this.articleData=res.data})},}使用v-for渲染数据到页面 查看详情到这里就完成了一个简单的显示文章列表的功能,文章详情页是查看详情的绑定事件文章列表:当点击时获取当前点击文章的id,根据不同的id跳转到对应的详情页
查看详情article(index){letids=this.articleData[index].idthis.$router.push({path:'../article/'+ids})},现在点击跳转到文章详情页,接下来要做的就是在详情页显示当前id对于下一篇文章的内容,我们需要在当前详情页加载完成的时候执行一个事件来获取文章的内容,在api中定义获取文章详情的api。js//获取单篇文章exportconstgetArticle=ids=>{returnaxios.get(`${base}/posts/${ids}`).then(res=>res.data);};引入并定义article.vue中的事件:从'../api/api'导入{getArticle};getarticle(){//获取idletids=this.$route.params.id//使用获取到的id请求apigetArticle(ids).then(res=>{this.articleData=res})},bindDefine事件并呈现文章结构
作者:{{articleData.author}}发??布时间:{{articleeData.date}}