Vue中axios的基础使用方式

简单的为大家介绍一下如何在vue中使用axios
废话不多说直接上代码:

基础使用

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title></title>
</head>

<body>
    <div id="root">
        <button @click="search">点击发送GET请求</button>
    </div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js"></script>
<script src="../JS/vue.js"></script>
<script>
    const vm = new Vue({
        el: "#root",
        methods: {
            search() {
                // 第一种方式
                // axios({
                // 请求方式
                //     method: "GET",
                // 请求的url
                //     url: "http://localhost:3000/posts"
                // }).then(res => {
                //     console.log(res);
                // })

                // 第二种方式 常用
                // 比较方便 第一个直接写url
                axios.get("http://localhost:3000/posts").then(res => {
                    console.log(res);
                })
            }
        },
    })
</script>
</html>
渲染页面

修改页面的数组让他重新解析就能达到渲染页面的目的了

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title></title>
</head>

<body>
    <div id="root">
        <button @click="search">点击发送GET请求</button>
        <ul>
            <li v-for="item in list" :key="item.id">
                {{item.id}}--{{item.title}}--{{item.author}}
            </li>
        </ul>
    </div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js"></script>
<script src="../JS/vue.js"></script>
<script>
    const vm = new Vue({
        el: "#root",
        data: {
            list: []
        },
        methods: {
            search() {
                // 第一种方式
                // axios({
                // 请求方式
                //     method: "GET",
                // 请求的url
                //     url: "http://localhost:3000/posts"
                // }).then(res => {
                //     console.log(res);
                // })

                // 第二种方式 常用
                // 比较方便 第一个直接写url
                axios.get("http://localhost:3000/posts").then(res => {
                    // console.log(res);
                    this.list = res.data
                })
            }
        },
    })
</script>
</html>

注:

如果碰到跨域问题怎么办
第一种:使用cors解决
第二种:在vueconfig里面配置proxy
上代码:

devServer: {
    proxy: {
      '/posts': {
        target: 'http://localhost:3000'
      }
    }
  },
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值