登录 主页

使用 vue 调用 API 接口来显示文章列表页面

2023-11-11 11:39AM

参考:https://vue_book.siwei.me/http_request.html

1. 在 src/components/ 文件夹下面创建博客列表文件。(我创建的是 BlogLIst.vue)

<template>
  <div>
    <table>
      <tr v-for="article in articles" :key="article.id">
        <div>{{ article.title }}</div>
      </tr>
    </table>
  </div>
</template>
<script>
export default {
  data () {
    return {
      title: '博客列表页',
      articles: [
      ]
    }
  },
  mounted () {
    this.$http.get('http://mysite/api/articles').then((response) => {
      console.info(response.body)
      this.articles = response.body.articles
    }, (response) => {
      console.error(response)
    })
  }
}
</script>
<style>
td {
  border-bottom: 1px solid grey;
}
</style>

2. 增加路由

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import BlogList from '@/components/BlogList'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/BlogList',
      name: 'BlogList',
      component: BlogList
    }
  ]
}) 

3. 设置 vue 开发服务器的代理

一般情况下,javascript 在浏览器是无法发送跨域请求的,所以我们需要在vuejs的"开发服务器"上做 个转发配置.

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: 'http://admin.meiyi.site', // 指定代理目标的基础路径
        changeOrigin: true, // 启用跨域
        pathRewrite: {
          '^/api': '' // 可选的,重写请求路径,将 '/api' 替换为空字符串
        }
      }
    },

}

4. 记得要安装 vue-resource 库,不然浏览器的 console 会一直报错:"TypeError: Cannot read properties of undefined (reading 'get')"

1) 使用下面这个命令:

$ npm install vue-resource

2) 在 Vue.js 应用程序的入口文件(通常是main.js)中,导入并使用vue-resource: 

import VueResource from 'vue-resource'

Vue.use(VueResource)

然后在浏览器刷新页面,就会发现已经可以了。

 

返回>>

登录

请登录后再发表评论。

评论列表:

目前还没有人发表评论