测试项目(四):前后端数据连接

好家伙,

 

测试用的vue3项目寄了,这里用回vue2

在前端,我们用axios发起网络请求

1.vue2中安装axios

npm install axios -S

随后在main.js中

import Vue from 'vue'
import App from './App.vue'
import router from './router'

import axios from 'axios';

Vue.config.productionTip = false

new Vue({
  router,
  axios,
  render: h => h(App)
}).$mount('#app')

 

来到我们的组件页面中,

<template>
  <div class="about">
    <table>
      <tr>
        <td>编号</td>
        <td>图书名称</td>
        <td>作者</td>
      </tr>
      <tr v-for="item in books">
        <td>{{item.id}}</td>
        <td>{{item.name}}</td>
        <td>{{item.author}}</td>

      </tr>
    </table>
  </div>
</template>

<script>
// @ is an alias to /src

import axios from 'axios'

export default {
  name: 'Home',
  data() {
    return {
      msg: '没有数据了',
      books: [
        {
          id: 1,
          name: '好书',
          author: '好人'
        },
        {
          id: 1,
          name: '好书',
          author: '好人'
        },
      ]
    }
  },
  created() {
    const _this=this;
    axios({
      method: "get",
      url: "http://localhost:8011/mydb/getUsers",
    }).then(res => {
      // this.data = res.data /* 将拿到的值,赋值给data */
      _this.books=res.data;
    })


  }
}
</script>

将网络请求写到生命周期函数created中

  created() {
    const _this=this;
    axios({
      method: "get",
      url: "http://localhost:8011/mydb/getUsers",
    }).then(res => {
      // this.data = res.data /* 将拿到的值,赋值给data */
      _this.books=res.data;
    })
  }

在这里,我们发起请求后,拿到的数据会返回到res中,我们再将res.data赋值给books,

这样在页面中,就可以看见真数据了

 

后端的没跑起来,请求接口暂时无法使用,

来到页面中

 

 

2.把后端跑起来

 

 

随后再解决一个跨域问题,解决方案如下

测试项目(三):在后端解决跨域问题 - 养肥胖虎 - 博客园 (cnblogs.com)

 

 

 

 (成功显示)

 

 

 

 

 

至此,前端成功拿到了数据库中的数据并把它渲染了出来 

 

呼,终于搞定了

posted @ 2022-10-14 00:00  养肥胖虎  阅读(97)  评论(0编辑  收藏  举报