前端知识(一)05 axios-谷粒学院

一、axios的作用

axios是独立于vue的一个项目,可以用于浏览器和node.js中发送ajax请求

二、axios实例

创建axios_pro文件夹

1、复制js资源

vue.min.js
axios.min.js

2、创建 axios.html

3、引入js

<script src="vue.min.js"></script>
<script src="axios.min.js"></script>

4、启动课程中心微服务

5、编写js

<script>
    new Vue({
        el: '#app',
        data: {
            teacherList: []
        },
        methods: {

            getTeacherList(){
                axios.get('http://localhost:8110/admin/edu/teacher/list').then(response => {
                    console.log(response)
                    this.teacherList = response.data.data.items
                }).catch(error=>{
                    //失败
                    console.log(error)
                })
            }
        }
    })
</script>

6、html渲染数据

<div id="app">
    <button @click="getTeacherList()">访问</button>

    <table>
        <tr v-for="item in teacherList">
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
        </tr>
    </table>
</div>

7、跨域

为什么会出现跨域问题?
出于浏览器的同源策略限制:
所谓同源(即指在同一个域)就是两个地址具有相同的协议(protocol),主机(host)和端口号(port)
同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。
同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能。
解决跨域问题:

@CrossOrigin //解决跨域问题

8、使用生命周期函数

和methods一个级别

created () {
    this.getTeacherList()
},

9、业务分层的简单实现

// 初始化axios设置,返回一个函数引用
initRequest () { 
    return axios.create({
        baseURL: 'http://localhost:8110', // api 的 base_url
        timeout: 5000 // 请求超时时间
    })
},

//api访问模块
teacherListApi (){
    let request = this.initRequest()
    return request({
        url: '/admin/edu/teacher/list',
        method: 'get'
    })
},

    
//获取讲师列表
getTeacherList2() {
    console.log('发送ajax请求2......')
    this.teacherListApi().then(response => {
        console.log(response)
        var result = response.data //r对象
        this.teacherList = result.data.items
    })
}
原文地址:https://www.cnblogs.com/smalldong/p/13636471.html