Vue axios

1. 准备工作

npm install axios

2. 示例代码

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script src="./node_modules/vue/dist/vue.js"></script>
    <script src="./node_modules/axios/dist/axios.js"></script>
</head>

<body>

    <div id="app">
        <ul>
            <li v-for="(item, index) in users" :key="index">
                {{ item }}
            </li>
        </ul>
    </div>

    <script>

        let vm = new Vue({
            data() {
                return {
                    users: []
                }
            },
            methods: {
                getData() {
                    axios.get('http://localhost:8080/getData', {
                        params: {
                            id: 1
                        }
                    })
                        .then(function (response) {
                            // 注意此处无法引用到users
                            // 使用this.users也无法引用到,因为加了this指的是axios
                            // 因此可以使用 vm.users
                            vm.users = response.data
                        })

                        // 如果then是箭头函数,可以使用this来访问users
                        // 因为使用箭头函数时,this指的是这一层的外层,即axios的外层vm
                        // .then(response => {
                        //     this.users = response.data;
                        // })
                        .catch(function (error) {
                            console.error(error)
                        });
                }
            },
            mounted() {
                this.getData();
            },


        }).$mount('#app')

    </script>

</body>

</html>

后端代码:

	@GetMapping("/getData")
    public ResponseEntity<List<String>> getData(Long id, HttpServletResponse response) {
        System.out.println(id);
        response.addHeader("access-control-allow-origin", "*");
        return new ResponseEntity(Arrays.asList("zhangsan", "lisi", "wangwu"), HttpStatus.OK);
    }

运行:
在这里插入图片描述
补充:
后端代码中如果不加这一行:

response.addHeader(“access-control-allow-origin”, “*”);

前端这边将报错:

has been blocked by CORS policy
这是浏览器 同源策略 问题,或者叫 跨域问题 。常见于用Chrome调试脚本的时候,需要加载的脚本和location不同源

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值