“Vue的前后端通信(axios)”的版本间的差异
来自CloudWiki
第64行: | 第64行: | ||
[[文件:vue2022041604.png|600px]] | [[文件:vue2022041604.png|600px]] | ||
+ | 读取具体单个数据: | ||
+ | |||
+ | <nowiki> | ||
+ | <!DOCTYPE html> | ||
+ | <html> | ||
+ | <head> | ||
+ | <meta charset="utf-8"> | ||
+ | <title>Vue 测试实例 - 菜鸟教程(runoob.com)</title> | ||
+ | <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script> | ||
+ | <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script> | ||
+ | </head> | ||
+ | <body> | ||
+ | <div id="app"> | ||
+ | {{ info }} | ||
+ | </div> | ||
+ | <script type = "text/javascript"> | ||
+ | new Vue({ | ||
+ | el: '#app', | ||
+ | data () { | ||
+ | return { | ||
+ | info: null | ||
+ | } | ||
+ | }, | ||
+ | mounted () { | ||
+ | axios | ||
+ | .get('http://127.0.0.1:5000/hello') | ||
+ | .then(response => ( | ||
+ | this.info = response.data.data['姓名'])) | ||
+ | .catch(function (error) { // 请求失败处理 | ||
+ | console.log(error); | ||
+ | }); | ||
+ | |||
+ | } | ||
+ | |||
+ | }) | ||
+ | </script> | ||
+ | </body> | ||
+ | </html> | ||
+ | |||
+ | |||
+ | </nowiki> | ||
+ | |||
+ | [[文件:vue2022041605.png|500px]] | ||
2022年4月16日 (六) 04:22的版本
axios简介
Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。
Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node.js 中。
Github开源地址: https://github.com/axios/axios
环境准备
安装axios
使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
或
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
后端准备
可参考Vue+Flask前后端传参,搭建一个Flask框架。
前后端通信
GET方法
使用 response.data 读取 JSON 数据:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue 测试实例 - 菜鸟教程(runoob.com)</title> <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script> <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script> </head> <body> <div id="app"> {{ info }} </div> <script type = "text/javascript"> new Vue({ el: '#app', data () { return { info: null } }, mounted () { axios .get('http://127.0.0.1:5000/hello') .then(response => (this.info = response.data)) .catch(function (error) { // 请求失败处理 console.log(error); }); } }) </script> </body> </html>
读取具体单个数据:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue 测试实例 - 菜鸟教程(runoob.com)</title> <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script> <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script> </head> <body> <div id="app"> {{ info }} </div> <script type = "text/javascript"> new Vue({ el: '#app', data () { return { info: null } }, mounted () { axios .get('http://127.0.0.1:5000/hello') .then(response => ( this.info = response.data.data['姓名'])) .catch(function (error) { // 请求失败处理 console.log(error); }); } }) </script> </body> </html>